<?php

namespace App\Libs\wrapper;

use App\Models\BaseModel;
use App\Models\Common\Constant;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\IFTTTHandler;
use PHPUnit\Runner\Exception;

class Spu extends Comm
{
//////////////////////////////////////////////// SPU
////////////////////// spu_config SPU配置表
    /**
     * 配置列表--数据
     * @param fid 父级id
     * @param name 名称
     * @param name_yw 英文名称
     * @param identifying 标识
     * @param type 类型：1.类目，2.颜色，3.尺码，4.材质，5.产品属性，6.包装状态，7.产品描述
     */
    public function config_list($data, $field = '')
    {
        $where = "1=1";
        // fid 父级id
        if (isset($data['fid'])) {
            $where .= " and sc.`fid`={$data['fid']}";
        }
        // name 名称
        if (!empty($data['name'])) {
            $where .= " and sc.`name` like '%{$data['name']}%'";
        }
        // name_yw 英文名称
        if (!empty($data['name_yw'])) {
            $where .= " and sc.`name_yw` like '%{$data['name_yw']}%'";
        }
        // identifying 标识
        if (!empty($data['identifying'])) {
            $where .= " and sc.`identifying`='{$data['identifying']}'";
        }
        //类型：1.类目，2.尺码，3.颜色，4.材质，5.产品属性，6.包装状态，7.产品描述
        if (!empty($data['type'])) {
            $where .= " and sc.`type`={$data['type']}";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        // 获取字段
        if (empty($field)) {
            $field = 'sc.*';
        }

        $sql = "select SQL_CALC_FOUND_ROWS {$field}
                from spu_config sc
                where {$where}
                order by sc.Id asc {$limit}";
//		return $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        $return['list'] = $list;
        return $return;
    }

    /**
     * 新增配置
     * @logic 名称唯一
     */
    public function config_add($data)
    {
//		return $data;
        // 同级中 名称、标识唯一
        $where_find = "";
        // name 名称
        if (!empty($data['name'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `name`='{$data['name']}'";
        }
        // name_yw 英文名称
        if (!empty($data['name_yw'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `name_yw`='{$data['name_yw']}'";
        }
        // identifying 标识
        if (!empty($data['identifying'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `identifying`='{$data['identifying']}'";
        }
        if (empty($where_find)) {
            return '$where_find为空';
        }
        $sql = "select *
				from spu_config
				where `type`={$data['type']} and ({$where_find})";
        $find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($find)) {
            if ((!empty($data['name'])) && ($find[0]['name'] == $data['name'])) {
                return '该名称已被使用';
            }
            if ((!empty($data['name_yw'])) && ($find[0]['name_yw'] == $data['name_yw'])) {
                return '该英文名称已被使用';
            }
            if ((!empty($data['identifying'])) && ($find[0]['identifying'] == $data['identifying'])) {
                return '该标识已被使用';
            }
        }

        //// 新增数据
        $field_arr = array('fid', 'name', 'name_yw', 'identifying', 'type');
        $field = '';
        $insert = '';
        foreach ($data as $k => $v) {
            if (in_array($k, $field_arr)) {
                $field .= ",`{$k}`";
                $insert .= ",'{$v}'";
            }
        }
        $field = substr($field, 1);
        $insert = substr($insert, 1);
        if (empty($field) || empty($insert)) {
            return '新增数据为空';
        }

        $sql = "insert into spu_config({$field}) values ({$insert})";
//		return $sql;
        $add = db::insert($sql);
        if ($add) {
            return 1;
        } else {
            return '新增失败';
        }
    }

    /**
     * 编辑配置
     * @param Id
     * @logic 名称唯一
     */
    public function config_update($data)
    {
        // 修改标识，检查标识是否已被绑定
//		return $data;
        if ((!empty($data['identifying'])) && (!empty($data['identifying_log'])) && $data['identifying'] != $data['identifying_log']) {
            if ($data['type'] == 1) {
                // 类目
                $sql = "select `Id`
					from `spu`
					where type_id_1={$data['Id']} or type_id_2={$data['Id']} or type_id_3={$data['Id']} or type_id_4={$data['Id']} or type_id_5={$data['Id']} or type_id_6={$data['Id']}";
            } else if ($data['type'] == 2) {
                // 颜色
                $sql = "select `Id`
					from `spu_sku`
					where color_id={$data['Id']}";
            } else if ($data['type'] == 3) {
                // 尺码
                $sql = "select `Id`
					from `spu_sku`
					where size_id={$data['Id']}";
            } else if ($data['type'] == 9) {
                // 款式
                $sql = "select `Id`
					from `spu_sku`
					where style_id={$data['Id']}";
            }

            $find_1 = json_decode(json_encode(db::select($sql)), true);
            if (!empty($find_1)) {
                return '已被绑定，不能修改';
            }
        }

        // 同级中 名称、标识唯一
        $where_find = "";
        // name 名称
        if (!empty($data['name'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `name`='{$data['name']}'";
        }
        // name_yw 英文名称
        if (!empty($data['name_yw'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `name_yw`='{$data['name_yw']}'";
        }
        // identifying 标识
        if (!empty($data['identifying'])) {
            $where_find .= empty($where_find) ? "`name`='{$data['name']}'" : " or `identifying`='{$data['identifying']}'";
        }
        if (empty($where_find)) {
            return '$where_find为空';
        }
        $sql = "select *
				from spu_config
				where `type`={$data['type']} and `Id`!={$data['Id']} and ({$where_find})";
        $find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($find)) {
            if ((!empty($data['name'])) && ($find[0]['name'] == $data['name'])) {
                return '该名称已被使用';
            }
            if ((!empty($data['name_yw'])) && ($find[0]['name_yw'] == $data['name_yw'])) {
                return '该英文名称已被使用';
            }
            if ((!empty($data['identifying'])) && ($find[0]['identifying'] == $data['identifying'])) {
                return '该标识已被使用';
            }
        }

        //// 修改数据
        $field_arr = array('fid', 'name', 'name_yw', 'identifying');
        $set = '';
        foreach ($data as $k => $v) {
            if ((in_array($k, $field_arr)) && (!empty($v))) {
                $set .= ",`{$k}`='{$v}'";
            }
        }
        if (empty($set)) {
            return '修改数据为空';
        }
        $set = substr($set, 1);

        $sql = "update spu_config
				set {$set}
				where `Id` = {$data['Id']}";
//		return $sql;
        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '编辑失败';
        }
    }

    /**
     * 删除配置
     * @param Id
     * @param type 类型：1.类目，2.颜色，3.尺码，4.材质，5.产品属性，6.包装形式，7.产品描述，8.包装材质，9.款式
     */
    public function config_del($data)
    {
        // 修改标识，检查标识是否已被绑定
        if (in_array($data['type'], array(1, 2, 3, 4, 5, 6, 7, 8, 9))) {
            if ($data['type'] == 1) {
                // 类目
                $sql = "select `Id`
					from `spu`
					where type_id_1={$data['Id']} or type_id_2={$data['Id']} or type_id_3={$data['Id']} or type_id_4={$data['Id']} or type_id_5={$data['Id']} or type_id_6={$data['Id']}";
            } else if ($data['type'] == 2) {
                // 颜色
                $sql = "select `Id`
					from `spu_sku`
					where color_id={$data['Id']}";
            } else if ($data['type'] == 3) {
                // 尺码
                $sql = "select `Id`
					from `spu_sku`
					where size_id={$data['Id']}";
            } else if ($data['type'] == 4) {
                // 材质
                $sql = "select `Id`
						from `spu`
						where material_id like '%{$data['Id']}%'";
            } else if ($data['type'] == 5) {
                // 材质
                $sql = "select `Id`
						from `spu`
						where productstate_id like '%{$data['Id']}%'";
            } else if ($data['type'] == 6) {
                // 包装形式
                $sql = "select `Id`
						from `spu`
						where pack_id like '%{$data['Id']}%'";
            } else if ($data['type'] == 7) {
                // 属性
                $sql = "select `Id`
						from `spu`
						where description_sj like '%{$data['Id']}%' or description_ys like '%{$data['Id']}%' or description_fg like '%{$data['Id']}%' or description_ch like '%{$data['Id']}%'";
            } else if ($data['type'] == 8) {
                // 包装材质
                $sql = "select `Id`
						from `spu`
						where pack_material_id like '%{$data['Id']}%'";
            } else if ($data['type'] == 9) {
                // 款式
                $sql = "select `Id`
						from `spu_sku`
						where style_id={$data['Id']}";
            }

            $find_1 = json_decode(json_encode(db::select($sql)), true);
            if (!empty($find_1)) {
                return '已被绑定，不能删除';
            }
        }

        $sql = "delete
				from `spu_config`
				where `Id`={$data['Id']}";
//		return $sql;
        $delete = db::delete($sql);
        if ($delete) {
            return 1;
        } else {
            return '删除失败';
        }
    }

////////////////////// 类目

    /**
     * 类目--Excel导入
     * @param file 文件流
     */
    public function category_import($data)
    {
        ////获取Excel文件数据
        //载入文档
        $objPHPExcelReader = \PHPExcel_IOFactory::load($data['file']['tmp_name']);
        $currentSheet = $objPHPExcelReader->getSheet(0);//读取第一个工作表(编号从 0 开始)
//		$allColumn = 'O';//取得总列数
        $allColumn = $currentSheet->getHighestColumn();//取得总列数
        $allRow = $currentSheet->getHighestRow();//取得总行数

        $add_list = array();
        /**从第1行开始输出*/
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            /**从第A列开始输出*/
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $key = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), 1)->getValue();//数据键值
                $val = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getValue();//数据
                $gva = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getFormattedValue();//数据

                if ($currentColumn == 'G') {
                    break;
                }
                //判断键名是否正确
                $array_key = array('大类名称', '大类标识', '二类名称', '二类标识', '三类名称', '三类标识');
                if (!in_array($key, $array_key)) {
                    return 'Excel数据格式不对,请下载Excel模板进行导入';
                }
                if (empty($val)) {
                    break;
                }

                if ($key == '大类名称') {
                    $add_list[$currentRow - 2]['name_1'] = $val;
                } else if ($key == '大类标识') {
                    $add_list[$currentRow - 2]['identifying_1'] = $val;
                } else if ($key == '二类名称') {
                    $add_list[$currentRow - 2]['name_2'] = $val;
                } else if ($key == '二类标识') {
                    $add_list[$currentRow - 2]['identifying_2'] = $val;
                } else if ($key == '三类名称') {
                    $add_list[$currentRow - 2]['name_3'] = $val;
                } else if ($key == '三类标识') {
                    $add_list[$currentRow - 2]['identifying_3'] = $val;
                }
            }
        }

        // 处理数据
        $list = array();
        foreach ($add_list as $k => $v) {
            // 大类
            $name_1 = array_column($list, 'name');// 提取数组某个键值
            $key_1 = array_search($v['name_1'], $name_1);// 字符串在数组的键值
            if ($key_1 === false) {
                // 不存在
                $list[] = array(
                    'name' => $v['name_1'],
                    'identifying' => $v['identifying_1'],
                    'children' => array()
                );

                $name_1 = array_column($list, 'name');
                $key_1 = array_search($v['name_1'], $name_1);
            }

            // 二类
            $name_2 = array_column($list[$key_1]['children'], 'name');
            $key_2 = array_search($v['name_2'], $name_2);
            if ($key_2 === false) {
                // 不存在
                $list[$key_1]['children'][] = array(
                    'name' => $v['name_2'],
                    'identifying' => $v['identifying_2'],
                    'children' => array()
                );

                $name_2 = array_column($list[$key_1]['children'], 'name');// 提取数组某个键值
                $key_2 = array_search($v['name_2'], $name_2);// 字符串在数组的键值
            }

            // 三类
            $name_3 = array_column($list[$key_1]['children'][$key_2]['children'], 'name');// 提取数组某个键值
            $key_3 = array_search($v['name_3'], $name_3);// 字符串在数组的键值
            if ($key_3 === false) {
                // 不存在
                $list[$key_1]['children'][$key_2]['children'][] = array(
                    'name' => $v['name_3'],
                    'identifying' => $v['identifying_3'],
                    'children' => array()
                );
            }
        }

        //// 存储数据
        if (empty($list)) {
            return 'Excel文件数据为空';
        }

        //添加数据
        foreach ($list as $k => $v) {
            //// 新增大类
            // 大类是否存在
            $sql = "select `Id`
						from spu_config
						where fid=0 and `type`=1 and (`name`='{$v['name']}' or `identifying`='{$v['identifying']}')
						limit 1";
            $find_1 = json_decode(json_encode(db::select($sql)), true);
            if (empty($find_1)) {
                // 新增大类
                $arr = array();
                $arr['fid'] = 0;
                $arr['name'] = $v['name'];
                $arr['identifying'] = $v['identifying'];
                $arr['type'] = 1;
                $add_1 = db::table('spu_config')->insertGetId($arr);
                if ($add_1) {
                    $fid_1 = $add_1;
                } else {
                    continue;
                }
            } else {
                $fid_1 = $find_1[0]['Id'];
            }

            //// 新增二类
            foreach ($v['children'] as $k1 => $v1) {
                // 二类是否存在
                $sql = "select `Id`
							from spu_config
							where fid={$fid_1} and `type`=1 and (`name`='{$v1['name']}' or `identifying`='{$v1['identifying']}')
							limit 1";
                $find_2 = json_decode(json_encode(db::select($sql)), true);
                if (empty($find_2)) {
                    // 新增二类
                    $arr = array();
                    $arr['fid'] = $fid_1;
                    $arr['name'] = $v1['name'];
                    $arr['identifying'] = $v1['identifying'];
                    $arr['type'] = 1;
                    $add_2 = db::table('spu_config')->insertGetId($arr);
                    if ($add_2) {
                        $fid_2 = $add_2;
                    } else {
                        continue;
                    }
                } else {
                    $fid_2 = $find_2[0]['Id'];
                }

                //// 新增三类
                foreach ($v1['children'] as $k2 => $v2) {
                    // 三类是否存在
                    $sql = "select `Id`
								from spu_config
								where fid={$fid_2} and `type`=1 and (`name`='{$v2['name']}' or `identifying`='{$v2['identifying']}')
								limit 1";
                    $find_3 = json_decode(json_encode(db::select($sql)), true);
                    if (empty($find_3)) {
                        // 新增三类
                        $arr = array();
                        $arr['fid'] = $fid_2;
                        $arr['name'] = $v2['name'];
                        $arr['identifying'] = $v2['identifying'];
                        $arr['type'] = 1;
                        $add_3 = db::table('spu_config')->insertGetId($arr);
                        if (!$add_3) {
                            continue;
                        }
                    }
                }
            }
        }

        return 1;

    }


////////////////////// spu列表

    /**
     * spu列表--数据
     * @param list_all 所有数据
     * @param spu
     * @parma user_kf_name 开发人
     * @parma platform_id 平台id
     * @param title 标题
     * @param type_id_1 大类spu_conserve
     * @param type_id_2 二类
     * @param type_id_3 三类
     * @param state 状态：1.未使用，2.待完善，3.待审核，4.未通过，5.已通过，6.已确认
     * @param create_time 创建时间
     */
    public function spu_list($data)
    {
        /*$sql = "select * from spu";
        $spu_data = json_decode(json_encode(db::select($sql)), true);
        foreach ($spu_data as $key=>$value){
            if($value['state']==6){
                $sql = "update spu
				set state=5
				where `Id` = {$value['Id']}";
                $update= db::update($sql);
            }
            $spu_id = $value['Id'];
            $insert['spu_id'] = $spu_id;
            $insert['supplier_id'] = $value['supplier_id'];
            $insert['supplier_hh'] = $value['supplier_hh'];
            $insert['purchase_url_1'] = $value['purchase_url_1'];
            $insert['purchase_url_2'] = $value['purchase_url_2'];
            $insert['purchase_price'] = $value['purchase_price'];
            $insert['day_sc'] = $value['day_sc'];
            $insert['day_ys'] = $value['day_ys'];
            $insert['day_rk'] = $value['day_rk'];
            $insert['day_cg'] = $value['day_cg'];
            $insert['is_spotgoods'] = $value['is_spotgoods'];
            $insert['is_mode'] = $value['is_mode'];
            $insert['is_mode'] = $value['number_qd'];
            $sql = "select * from spu_supply where spu_id={$spu_id} ";
            $find = json_decode(json_encode(db::select($sql)), true);
            if(empty($find)){
                $res = DB::table('spu_supply')->insert($insert);
            }
            //var_dump($value);
        }die;*/
        //var_dump($spu_data);die;
        //var_dump($data);die;
        //$data['no_state'] = 5;
        $where = "1=1";
        //list_all 所有数据
        if (!$data['list_all']) {
            $where .= " and s.`user_kf`={$data['user_info']['Id']}";
        }
        // title 标题
        if (!empty($data['title'])) {
            $where .= " and s.`title` like '%{$data['title']}%'";
        }
        // spu
        if (!empty($data['spu'])) {
            $where .= " and s.`spu` like '%{$data['spu']}%'";
        }
        // platform_id 平台id
        if (!empty($data['platform_id'])) {
            $where .= " and s.`platform_id`={$data['platform_id']}";
        }
        // user_kf_name 开发人
        if (!empty($data['user_kf_name'])) {
            $where .= " and u.`account` like '%{$data['user_kf_name']}%'";
        }
        // type_id_1 大类
        if (!empty($data['type_id_1'])) {
            $where .= " and s.`type_id_1`={$data['type_id_1']}";
        }
        // type_id_2 二类
        if (!empty($data['type_id_2'])) {
            $where .= " and s.`type_id_2`={$data['type_id_2']}";
        }
        // type_id_3 三类
        if (!empty($data['type_id_3'])) {
            $where .= " and s.`type_id_3`={$data['type_id_3']}";
        }
        //$data['no_state'] = 5;
        // state 状态：1.未使用，2.待完善，3.待审核，4.未通过，5.已通过，6.已确认
        if (!empty($data['state'])) {
            $where .= " and s.`state`={$data['state']}";
        }

        // state 状态：1.未使用，2.待完善，3.待审核，4.未通过，5.已通过，6.已确认
        //var_dump($data['no_state']);die;
        if (isset($data['no_state'])) {
            if (!empty($data['no_state'])) {
                $where .= " and s.`state`!={$data['no_state']}";
            }

        }

//var_dump($data);die;
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $data['create_time'][1] = $data['create_time'][1] . ' 24:00:00';
            $where .= " and s.create_time>='{$data['create_time'][0]}' and s.create_time<='{$data['create_time'][1]}'";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }
        //var_dump($where);die;
        $sql = "select SQL_CALC_FOUND_ROWS s.*, p.name as platform_name, t1.name as type_1, t2.name as type_2, t3.name as type_3, u.account as user_kf_name,us.account as cj_name
				from `spu` s
				left join platform p on p.Id = s.platform_id
				left join spu_config t1 on t1.Id = s.type_id_1
				left join spu_config t2 on t2.Id = s.type_id_2
				left join spu_config t3 on t3.Id = s.type_id_3
				left join users u on u.Id = s.user_kf
				left join users us on us.Id=s.user_cj
				where {$where}
				order by s.Id desc {$limit}";
        //var_dump($sql);die;
        $list = json_decode(json_encode(db::select($sql)), true);
        //var_dump($list);die;
//				left join spu_supply su on su.spu_id=s.Id
        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        $return['list'] = $list;
        //var_dump($return);die;
        return $return;
    }


    /**
     * spu预览
     * @param platform_id 平台id
     * @param type_id_1 大类id
     * @param type_id_2 二类id
     * @param type_id_3 三类id
     * @logic 获取数字编号，数字编号在大类三类组合下排序
     */
    public function spu_preview($data)
    {
        // lpad(`number`, 5, 0) as aa   左边补0
        $sql = "select `number`
				from `spu`
				where platform_id={$data['platform_id']} and type_id_1={$data['type_id_1']} and type_id_3={$data['type_id_3']}
				order by `Id` desc
				limit 1";
        $find = json_decode(json_encode(db::select($sql)), true);
        if (empty($find)) {
            $number = 1;
        } else {
            $number = ++$find[0]['number'];
        }

        $number_new = str_pad($number, 5, 0, STR_PAD_LEFT);

        // 平台、大类、三类
        $sql = "select (select `identifying` from platform where `Id`={$data['platform_id']} limit 1) as platform_identifying,
			       (select `identifying` from spu_config where `Id`={$data['type_id_1']} limit 1) as type_identifying_1,
			       (select `identifying` from spu_config where `Id`={$data['type_id_3']} limit 1) as type_identifying_3 ";
        $info = json_decode(json_encode(db::select($sql)), true);
        // spu
        $spu = $info[0]['platform_identifying'] . '' . $info[0]['type_identifying_1'] . '' . $info[0]['type_identifying_3'] . '' . $number_new;

        $info[0]['number'] = $number;
        $info[0]['spu'] = $spu;
        return $info[0];
    }

    /**
     * 新增spu
     * @param platform_id 平台id
     * @param type_id_1 大类id
     * @param type_id_2 二类id
     */
    public function spu_add($data)
    {
        // 获取数字编号
        $spu_info = $this->spu_preview($data);
        $data['number'] = $spu_info['number'];
        $data['spu'] = $spu_info['spu'];

        //// 新增数据
        $insert['user_cj'] = $data['user_cj'];
        $insert['user_kf'] = $data['user_kf'];
        $insert['number'] = $data['number'];
        $insert['platform_id'] = $data['platform_id'];
        $insert['spu'] = $data['spu'];
        $insert['type_id_1'] = $data['type_id_1'];
        $insert['type_id_2'] = $data['type_id_2'];
        $insert['type_id_3'] = $data['type_id_3'];
        db::beginTransaction();    //开启事务
        $add_spu = DB::table('spu')->insertGetId($insert);
        if(!$add_spu){
	        db::rollback();    //事务回滚
	        return '新增spu失败';
        }
        
        //// 新增spu供应商
	    $sql = "insert into `spu_supply`(spu_id)
					values ({$add_spu})";
	    $add = db::insert($sql);
	    if(!$add_spu){
		    db::rollback();    //事务回滚
		    return '新增spu_supply失败';
	    }
		
	    db::commit();    //事物确认
	    return 1;



    }

////////////////////// spu详情页面

    /**
     * 配置数据
     * @param Id spu的id
     * 数据：spu基本信息、用户信息、第三类目(根据二类获取)、颜色、尺码、产品描述、供应商、平台
     */
    public function get_allocation($data)
    {
        //var_dump($data);die;
        ///////////////////////////////////// 已有数据
        //// spu基本信息：大类、二类、三类
        $sql = "select s.*,s.Id,su.*,u.account as cj_name,
					if(s.user_cg=0, '', s.user_cg) as user_cg,
					if(s.supplier_id=0, '', s.supplier_id) as supplier_id,
					if(s.type_id_4=0, '', s.type_id_4) as type_id_4,
					if(s.type_id_5=0, '', s.type_id_5) as type_id_5,
					if(s.type_id_6=0, '', s.type_id_6) as type_id_6,
					(select `name` from spu_config where Id=s.type_id_1) as type_id_1_name,
					(select `name` from spu_config where Id=s.type_id_2) as type_id_2_name,
					(select `name` from spu_config where Id=s.type_id_3) as type_id_3_name,sup.name as supplier_name,su.Id as supply_id,s.Id as Id,su.supplier_id as supplier_id
				from `spu` s
				left join spu_supply su on su.spu_id=s.Id
				left join suppliers sup on sup.Id=su.supplier_id
				left join users u on u.Id=s.user_cj
				where s.`Id`={$data['Id']}
				limit 1";//,su.supplier_id as supplier_id
        //var_dump($sql);die;
        $spu_info = json_decode(json_encode(db::select($sql)), true);
        //var_dump($spu_info);die;
        if (empty($spu_info)) {
            return 'spu不存在';
        }
        // 处理数据
        $spu_info[0]['title_rand'] = !empty($spu_info[0]['title_rand']) ? explode(",", $spu_info[0]['title_rand']) : array();
        //var_dump($spu_info);die;
        $spu_info[0]['label'] = !empty($spu_info[0]['label']) ? explode(",", $spu_info[0]['label']) : array();
        $spu_info[0]['extra_img'] = !empty($spu_info[0]['extra_img']) ? explode(",", $spu_info[0]['extra_img']) : array();
        $spu_info[0]['description_sj'] = !empty($spu_info[0]['description_sj']) ? explode(",", $spu_info[0]['description_sj']) : array();
        $spu_info[0]['description_ys'] = !empty($spu_info[0]['description_ys']) ? explode(",", $spu_info[0]['description_ys']) : array();
        $spu_info[0]['description_fg'] = !empty($spu_info[0]['description_fg']) ? explode(",", $spu_info[0]['description_fg']) : array();
        $spu_info[0]['description_ch'] = !empty($spu_info[0]['description_ch']) ? explode(",", $spu_info[0]['description_ch']) : array();
        $spu_info[0]['pack_id'] = !empty($spu_info[0]['pack_id']) ? explode(",", $spu_info[0]['pack_id']) : array();
        $spu_info[0]['pack_material_id'] = !empty($spu_info[0]['pack_material_id']) ? explode(",", $spu_info[0]['pack_material_id']) : array();
        $spu_info[0]['material_id'] = !empty($spu_info[0]['material_id']) ? explode(",", $spu_info[0]['material_id']) : array();
        $spu_info[0]['productstate_id'] = !empty($spu_info[0]['productstate_id']) ? explode(",", $spu_info[0]['productstate_id']) : array();
        //$size_chart = array();
        $spu_info[0]['size_chart'] = !empty($spu_info[0]['size_chart']) ? json_decode($spu_info[0]['size_chart'],true) : array();

        //// 尺码
        $size_info = array(
            'size_f' => '',
            'size' => array()

        );
        $sql = "select aa.*
		       from spu_sku ss
	           inner join (select fp.`Id` as size_f, p.Id, p.identifying, p.name
	                             from spu_config p
	                             inner join spu_config fp on fp.Id=p.fid
	                             where p.`type`=3
	                         ) aa on aa.Id = ss.size_id
			   where ss.spu_id={$data['Id']}
	           group by size_id";
        $size_list = json_decode(json_encode(db::select($sql)), true);
        if (!empty($size_list)) {
            $size_info['size_f'] = $size_list[0]['size_f'];
            foreach ($size_list as $k => $v) {
                $size_info['size'][] = $v['Id'] . '-' . $v['identifying'] . '-' . $v['name'];
            }
        }

        //// 款式
        $style_info = array();
        $sql = "select aa.*
		       from spu_sku ss
	           inner join (select *
	                             from spu_config p
	                             where p.`type`=9
	                         ) aa on aa.Id = ss.style_id
			   where ss.spu_id={$data['Id']}
	           group by style_id";
        $style = json_decode(json_encode(db::select($sql)), true);
        if (!empty($style)) {
            foreach ($style as $k => $v) {
                $style_info[] = $v['Id'] . '-' . $v['identifying'] . '-' . $v['name'];
            }
        }

        //// 颜色
        $color_info = array();
        $sql = "select sc.*
		       from spu_sku ss
	           inner join (select *
	                             from spu_config p
	                             where p.`type`=2
	                         ) sc on sc.Id = ss.color_id
			   where ss.spu_id={$data['Id']}
	           group by ss.color_id";
        $color_list = json_decode(json_encode(db::select($sql)), true);
        if (!empty($color_list)) {
            foreach ($color_list as $k => $v) {
                $color_info[] = $v['Id'] . '-' . $v['identifying'] . '-' . $v['name'];
            }
        }

        //// 图片
        $img_info = array();
        $sql = "select cr.Id as color_id, cr.name as color_name, cr.identifying as color_identifying,
                    se.Id as style_id, se.name as style_name, se.identifying as style_identifying, sc.name as size_name, sc.identifying as size_identifying, ss.img_info,ss.*
		       from spu_sku ss
	            inner join (select *
	                             from spu_config p
	                             where p.`type`=2
	                         ) cr on cr.Id = ss.color_id
                inner join (select *
	                             from spu_config p
	                             where p.`type`=9
	                         ) se on se.Id = ss.style_id
	            inner join (select *
	                             from spu_config p
	                             where p.`type`=3
	                         ) sc on sc.Id = ss.size_id
			   where ss.spu_id={$data['Id']}
	           group by ss.color_id, ss.style_id,ss.size_id";
        $img_list = json_decode(json_encode(db::select($sql)), true);
       // var_dump($img_list);die;
        foreach ($img_list as $k => $v) {
            $imgs = empty($v['img_info']) ? array() : explode(",", $v['img_info']);
            $arr = array(
                'sku' => $v['sku'],
                'title' => $v['title'],
                'purchase_price' => $v['purchase_price'],
                'weight_m' => $v['weight_m'],
                'color_id' => $v['color_id'],
                'color_identifying' => $v['color_identifying'],
                'color_name' => $v['color_name'],
                'style_id' => $v['style_id'],
                'style_identifying' => $v['style_identifying'],
                'style_name' => $v['style_name'],
                'size_id' => $v['size_id'],
                'size_identifying' => $v['size_identifying'],
                'size_name' => $v['style_name'],
                'is_upload' => (count($imgs) == 0 ? 1 : 2),
                'ref' => 'color' . $v['color_id'] . $v['style_id'],
                'img_info' => $imgs
            );
            $img_info[] = $arr;
        }
        //var_dump($img_info);die;

        //// 定价
        $sql = "select Id, spu_id, url, percentage_mll, is_recommend,
                  if(platform_id=0, '', platform_id) as platform_id,
					if(country_id=0, '', country_id) as country_id,
					if(price_hs=0, '', price_hs) as price_hs,
					if(price_sc=0, '', price_sc) as price_sc,
					if(price_jy=0, '', price_jy) as price_jy
				from `spu_price` sp
				where sp.`spu_id`={$data['Id']}";
        $price_info = json_decode(json_encode(db::select($sql)), true);

        ///////////////////////////////////// 配置数据
        //// 用户列表
        $sql = "select `Id`, `account`
				from users
				where `state`=1";
        $user_list = json_decode(json_encode(db::select($sql)), true);

        //// 颜色
        $sql = "select *
				from spu_config
				where `type`=2";
        $color_list = json_decode(json_encode(db::select($sql)), true);

        //// 尺码规格
        $sql = "select *
				from spu_config
				where `type`=3 and `fid`=0";
        $specs_list = json_decode(json_encode(db::select($sql)), true);

        //// 类型：1.类目，2.颜色，3.尺码，4.材质，5.产品属性，6.包装形式，7.产品描述，8.包装材质，9.款式
        $sql = "select *
				from spu_config
				where `type` in (4, 5, 6, 7, 8, 9)";
        $attribute = json_decode(json_encode(db::select($sql)), true);
        // 产品描述
        $attribute_sj = array();
        $attribute_ys = array();
        $attribute_fg = array();
        $attribute_ch = array();
        // 包装状态
        $pack_list = array();
        // 材质
        $material_f = array();
        $material_fid = array();
        $material_son = array();
        // 产品属性
        $productstate_f = array();
        $productstate_fid = array();
        $productstate_son = array();
        foreach ($attribute as $k => $v) {
            $v['Id'] = strval($v['Id']);
            if ($v['type'] == 4) {
                // 材质
                if ($v['fid'] == 0) {
                    $material_f[] = $v;
                    $material_fid[] = $v['Id'];
                } else {
                    $material_son[] = $v;
                }
            } else if ($v['type'] == 5) {
                // 产品属性
                if ($v['fid'] == 0) {
                    $productstate_f[] = $v;
                    $productstate_fid[] = $v['Id'];
                } else {
                    $productstate_son[] = $v;
                }
            } else if ($v['type'] == 6) {
                // 包装形式
                $pack_list[] = $v;
            } else if ($v['type'] == 7) {
                // 产品描述
                if ($v['fid'] == 2) {
                    $attribute_sj[] = $v;
                } else if ($v['fid'] == 3) {
                    $attribute_fg[] = $v;
                } else if ($v['fid'] == 4) {
                    $attribute_ys[] = $v;
                } else if ($v['fid'] == 5) {
                    $attribute_ch[] = $v;
                }
            } else if ($v['type'] == 8) {
                // 包装材质
                $pack_material_list[] = $v;
            } else if ($v['type'] == 9) {
                // 款式
                $style_list[] = $v;
            }
        }

        // 材质--处理数据
        if (!empty($material_f)) {
            foreach ($material_son as $k => $v) {
                $a = array_search($v['fid'], $material_fid);
                if ($a !== false) {
                    $material_f[$a]['children'][] = $v;
                }
            }
        }
        // 产品属性--处理数据
        if (!empty($productstate_f)) {
            foreach ($productstate_son as $k => $v) {
                $a = array_search($v['fid'], $productstate_fid);
                if ($a !== false) {
                    $productstate_f[$a]['children'][] = $v;
                }
            }
        }

        //// 供应商
        $sql = "select `Id`, `name`
				from suppliers";
        $supplier_list = json_decode(json_encode(db::select($sql)), true);

        //// 平台
        $sql = "select *
				from platform
				where `state`=1";
        $platform_list = json_decode(json_encode(db::select($sql)), true);

        //// 国家
        $sql = "select *
				from countrys
				where `state`=1";
        $country_list = json_decode(json_encode(db::select($sql)), true);

        //// 返回数据
        $return = array();
        //// 已有数据
        $return['have']['spu_info'] = $spu_info[0];// spu基本信息
        $return['have']['size_info'] = $size_info;// 尺码
        $return['have']['style_info'] = $style_info;// 款式
        $return['have']['color_info'] = $color_info;// 颜色
        $return['have']['img_info'] = $img_info;// 图片
        $return['have']['price_info'] = $price_info;// 定价

        //// 配置数据
        $return['allocation']['user_list'] = $user_list;// 用户列表
        $return['allocation']['color_list'] = $color_list;// 颜色
        $return['allocation']['specs_list'] = $specs_list;// 尺码
        $return['allocation']['style_list'] = $style_list;// 款式

        // 场景描述
        $return['allocation']['attribute_sj'] = $attribute_sj;// 设计
        $return['allocation']['attribute_fg'] = $attribute_fg;// 风格
        $return['allocation']['attribute_ys'] = $attribute_ys;// 元素
        $return['allocation']['attribute_ch'] = $attribute_ch;// 场景

        $return['allocation']['supplier_list'] = $supplier_list;// 供应商
        $return['allocation']['platform_list'] = $platform_list;// 平台
        $return['allocation']['country_list'] = $country_list;// 国家

        $return['allocation']['pack_list'] = $pack_list;// 包装形式
        $return['allocation']['pack_material_list'] = $pack_material_list;// 包装材质
        $return['allocation']['material_list'] = $material_f;// 材质
        $return['allocation']['productstate_list'] = $productstate_f;// 产品属性
        //var_dump($return);die;
        return $return;

    }

    /**
     * spu保存信息
     * @param basic array 基本信息
     * @param color array 颜色
     * @param size array 尺码
     * @param style array 款式
     * @param img array 图片
     * @param price array 定价
     * @param pack array 包装
     * @param material array 材质
     * @param productstate array 产品属性
     */
    public function spu_conserve($data)
    {
        db::beginTransaction();    //开启事务

        //// 保存spu信息
        $set_basic = '';
		if(!empty($data['basic']['title'])){
			// 产品名称
			$title = str_replace("'", "\'", $data['basic']['title']);
			$set_basic .= ",`title`='{$title}'";
		}
	    if(!empty($data['basic']['title_en'])){
		    // 英文标题
		    $title_en = str_replace("'", "\'", $data['basic']['title_en']);
		    $set_basic .= ",`title_en`='{$title_en}'";
	    }
	    if(!empty($data['basic']['title_rand'])){
		    //英文变动标题
		    $title_rand = implode(',',$data['basic']['title_rand']);
		    $title_rand = str_replace("'", "\'", $title_rand);
		    $set_basic .= ",`title_rand`='{$title_rand}'";
	    }
        if(!empty($data['basic']['label'])){
	        //标签
            $label = implode(',',$data['basic']['label']);
	        $label = str_replace("'", "\'", $label);
            $set_basic .= ",`label`='{$label}'";
        }
        $set_basic .= !empty($data['basic']['brand']) ? ",`brand`='{$data['basic']['brand']}'" : '';//品牌
        $set_basic .= !empty($data['basic']['model']) ? ",`model`='{$data['basic']['model']}'" : '';//型号
	    $set_basic .= !empty($data['basic']['main_img']) ? ",`main_img`='{$data['basic']['main_img']}'" : '';//主图
	    if(!empty($data['basic']['extra_img'])){
	        //附图
            $extra_img = implode(',',$data['basic']['extra_img']);
            $set_basic .= ",`extra_img`='{$extra_img}'";
        }
        if(!empty($data['basic']['size_chart'])){
	        //尺码表
            $size_chart = json_encode($data['basic']['size_chart']);
            $set_basic .= ",`size_chart`='{$size_chart}'";
        }
        $set_basic .= !empty($data['basic']['user_kf']) ? ",`user_kf`={$data['basic']['user_kf']}" : '';
        $set_basic .= !empty($data['basic']['user_cg']) ? ",`user_cg`={$data['basic']['user_cg']}" : '';
        $set_basic .= !empty($data['basic']['level']) ? ",`level`='{$data['basic']['level']}'" : '';
        $set_basic .= !empty($data['basic']['type_id_4']) ? ",`type_id_4`={$data['basic']['type_id_4']}" : '';
        $set_basic .= !empty($data['basic']['type_id_5']) ? ",`type_id_5`={$data['basic']['type_id_5']}" : '';
        $set_basic .= !empty($data['basic']['type_id_6']) ? ",`type_id_6`={$data['basic']['type_id_6']}" : '';
        $set_basic .= !empty($data['basic']['file_fj']) ? ",`file_fj`='{$data['basic']['file_fj']}'" : '';
        $set_basic .= !empty($data['basic']['state']) ? ",`state`={$data['basic']['state']}" : '';
        $set_basic .= !empty($data['basic']['weight_j']) ? ",`weight_j`='{$data['basic']['weight_j']}'" : '';
        $set_basic .= !empty($data['basic']['weight_m']) ? ",`weight_m`='{$data['basic']['weight_m']}'" : '';
        $set_basic .= !empty($data['basic']['packing_size_c']) ? ",`packing_size_c`={$data['basic']['packing_size_c']}" : '';
        $set_basic .= !empty($data['basic']['packing_size_k']) ? ",`packing_size_k`={$data['basic']['packing_size_k']}" : '';
        $set_basic .= !empty($data['basic']['packing_size_g']) ? ",`packing_size_g`={$data['basic']['packing_size_g']}" : '';
        $set_basic .= !empty($data['basic']['parameter_info']) ? ",`parameter_info`=".'"'.$data['basic']['parameter_info'].'"' : '';
        // 产品描述
        // 设计
        if (!empty($data['basic']['description_sj'])) {
            $description_sj = implode(',', $data['basic']['description_sj']);
            $set_basic .= !empty($description_sj) ? ",`description_sj`='{$description_sj}'" : '';
        } else {
            $set_basic .= ",`description_sj`=''";
        }
        // 元素
        if (!empty($data['basic']['description_ys'])) {
            $description_ys = implode(',', $data['basic']['description_ys']);
            $set_basic .= !empty($description_ys) ? ",`description_ys`='{$description_ys}'" : '';
        } else {
            $set_basic .= ",`description_ys`=''";
        }
        // 风格
        if (!empty($data['basic']['description_fg'])) {
            $description_fg = implode(',', $data['basic']['description_fg']);
            $set_basic .= !empty($description_fg) ? ",`description_fg`='{$description_fg}'" : '';
        } else {
            $set_basic .= ",`description_fg`=''";
        }
        // 场合
        if (!empty($data['basic']['description_ch'])) {
            $description_ch = implode(',', $data['basic']['description_ch']);
            $set_basic .= !empty($description_ch) ? ",`description_ch`='{$description_ch}'" : '';
        } else {
            $set_basic .= ",`description_ch`=''";
        }
        // 材质
        if (!empty($data['basic']['material_id'])) {
            $material_id = implode(',', $data['basic']['material_id']);
            $set_basic .= !empty($material_id) ? ",`material_id`='{$material_id}'" : '';
        } else {
            $set_basic .= ",`material_id`=''";
        }

        // 包装
        // 包装形式
        if (!empty($data['basic']['pack_id'])) {
            $pack_id = implode(',', $data['basic']['pack_id']);
            $set_basic .= !empty($pack_id) ? ",`pack_id`='{$pack_id}'" : '';
        } else {
            $set_basic .= ",`pack_id`=''";
        }
        // 包装材质
        if (!empty($data['basic']['pack_material_id'])) {
            $pack_material_id = implode(',', $data['basic']['pack_material_id']);
            $set_basic .= !empty($pack_material_id) ? ",`pack_material_id`='{$pack_material_id}'" : '';
        } else {
            $set_basic .= ",`pack_material_id`=''";
        }
        // 产品属性
        if (!empty($data['basic']['productstate_id'])) {
            $productstate_id = implode(',', $data['basic']['productstate_id']);
            $set_basic .= !empty($productstate_id) ? ",`productstate_id`='{$productstate_id}'" : '';
        } else {
            $set_basic .= ",`productstate_id`=''";
        }
		
        $set_basic = substr($set_basic, 1);
        $sql = "update `spu`
					set {$set_basic}
					where `Id` = {$data['basic']['Id']}";
        $update_spu = db::update($sql);
        if ($update_spu === false) {
            db::rollback();    //事务回滚
            return '修改spu信息失败';
        }
		
	    //// 更新供应商信息
	    $set_supply = '';
	    $set_supply .= !empty($data['basic']['supplier_id']) ? ",`supplier_id`={$data['basic']['supplier_id']}" : '';
	    $set_supply .= !empty($data['basic']['purchase_price']) ? ",`purchase_price`='{$data['basic']['purchase_price']}'" : '';
	    $set_supply .= !empty($data['basic']['supplier_hh']) ? ",`supplier_hh`='{$data['basic']['supplier_hh']}'" : ",`supplier_hh`=''";
	    $set_supply .= !empty($data['basic']['purchase_url_1']) ? ",`purchase_url_1`='{$data['basic']['purchase_url_1']}'" : '';
	    $set_supply .= !empty($data['basic']['purchase_url_2']) ? ",`purchase_url_2`='{$data['basic']['purchase_url_2']}'" : '';
	    $set_supply .= !empty($data['basic']['number_qd']) ? ",`number_qd`='{$data['basic']['number_qd']}'" : '';
	    $set_supply .= !empty($data['basic']['day_sc']) ? ",`day_sc`={$data['basic']['day_sc']}" : '';
	    $set_supply .= !empty($data['basic']['day_ys']) ? ",`day_ys`={$data['basic']['day_ys']}" : '';
	    $set_supply .= !empty($data['basic']['day_rk']) ? ",`day_rk`={$data['basic']['day_rk']}" : '';
	    $set_supply .= !empty($data['basic']['day_cg']) ? ",`day_cg`={$data['basic']['day_cg']}" : '';
	    $set_supply .= !empty($data['basic']['is_spotgoods']) ? ",`is_spotgoods`={$data['basic']['is_spotgoods']}" : '';
	    $set_supply .= !empty($data['basic']['is_mode']) ? ",`is_mode`={$data['basic']['is_mode']}" : '';
	    $set_supply .= !empty($data['basic']['is_imitation']) ? ",`is_imitation`={$data['basic']['is_imitation']}" : '';
        if(!empty($set_supply)){
	        $set_supply = substr($set_supply, 1);
            $sql = "update `spu_supply`
						set {$set_supply}
						where `spu_id` = {$data['basic']['Id']}";
            $update_supply = db::update($sql);
//            $sql1 = "update `spu`
//						set {$set_supply}
//						where `Id` = {$data['basic']['Id']}";
//            $update_spu = db::update($sql1);
        }
        //var_dump($data['basic']['Id']);die;
        //// sku
        if ((!empty($data['color'])) && (!empty($data['size'])) && (!empty($data['style']))) {
            // 删除sku
            $sql = "delete 
						from spu_sku
						where spu_id={$data['basic']['Id']}";
            //var_dump($sql);die;
            $res = db::delete($sql);
            //var_dump($res);die;
            // 用于查询对应图片
            $have_img = array();
  /*          if(isset($data['img'])){

            }
            foreach ($data['img'] as $k => $v) {
                $have_img[] = $v['color_id'] . $v['style_id'];
            }*/

            // 新增
            $sku = $data['img'];
            $spu_id = $data['basic']['Id'];
            //var_dump($spu_id);die;
            foreach ($sku as $key=>$value){
                $color_identifying = $value['color_identifying'];
                $size_identifying = $value['size_identifying'];
                $style_identifying = $value['style_identifying'];
                //$sku = $data['basic']['spu'] . '_' . $color_identifying . '_' . $size_identifying . '_' . $style_identifying;
                $sku = $value['sku'];
                $color_name = $value['color_name'];
                $size_name = $value['size_name'];
                $style_name = $value['style_name'];
                $sku_title = $data['basic']['title'];
                if (!empty($data['basic']['supplier_hh'])) {
                    $sku_title .= "({$data['basic']['supplier_hh']})";
                }
                $sku_title .= '-' . $color_name . '-' . $size_name . '-' . $style_name;
                $color_id = $value['color_id'];
                $size_id = $value['size_id'];
                $style_id = $value['style_id'];
                $img_zt = isset($value['img_info']) ? $value['img_info'][0]:'';
//                if(!empty($img_zt)){
//                    unset($value['img_info'][0]);
//                }
                $purchase_price = isset($value['purchase_price']) ? $value['purchase_price']: '';
                $weight_m = isset($value['weight_m']) ? $value['weight_m']: '';
                $weight_j = isset($data['basic']['weight_j'])? $data['basic']['weight_j']: '';
                $img_info = isset($value['img_info']) ? implode(',',$value['img_info']): '';
                $sql = "insert into `spu_sku` (`spu_id`, `sku`, `title`, `color_id`, `size_id`, `style_id`, `purchase_price`, `weight_j`, `weight_m`,`img_zt`, `img_info`)
							values ($spu_id,'{$sku}','{$sku_title}',{$color_id},{$size_id},{$style_id},'{$purchase_price}','{$weight_j}','{$weight_m}','{$img_zt}','{$img_info}')
							on duplicate key update `title`=values(`title`),`purchase_price`=values(`purchase_price`),`img_zt`=values(`img_zt`),`img_info`=values(`img_info`)";
                //var_dump($sql);die;
                $add_sku = db::insert($sql);
	            if (!$add_sku) {
		            db::rollback();    //事务回滚
		            return '操作sku失败';
	            }
            };
        }

        // 发送消息
        if ($data['basic']['state'] == 3) {
            /*
            $content = "SPU：{$data['basic']['spu']}，请审核！";
            $sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
                        values ({$data['user_fs']}, {$data['user_js']}, '任务内消息', '{$content}', {$data['basic']['Id']}, 2, 1, now())";
            db::insert($sql);*/
        }
		
        db::commit();    //事物确认
        return 1;
    }

    /**
     * spu审核
     * @param spu_id
     * @param handle_desc 处理说明
     * @param state 状态：1.未使用，2.待完善，3.待审核，4.未通过，5.已通过，6.已确认
     */
    public function spu_examine($data)
    {
        // 获取spu 信息
        $sql = "select s.state, s.user_cj
				from `spu` s
				where s.`Id`={$data['spu_id']}
				limit 1";
        $find_spu = json_decode(json_encode(db::select($sql)), true);
        if (empty($find_spu)) {
            return '该SPU不存在';
        } else if ($find_spu[0]['state'] != 3) {
            return '当前不是审核状态';
        } else if ($find_spu[0]['state'] == $data['state']) {
            return 1;
        }

        // 编辑信息
        $set = "`state`={$data['state']}, `user_cl`={$data['user_info']['Id']}, `handle_time`=now()";
        // handle_desc 处理说明
        if (!empty($data['handle_desc'])) {
            $set .= ", `handle_desc`='{$data['handle_desc']}'";
        }

        $sql = "update `spu`
				set {$set}
				where `Id` = {$data['spu_id']}";
        $update = db::update($sql);
        if ($update === false) {
            return '修改SPU数据失败';
        }

        // 发送消息
        /*
        if($data['state'] == 4){
            $content = "SPU：{$data['basic']['spu']}，审核未通过！";
        }else if($data['state'] == 5){
            $content = "SPU：{$data['basic']['spu']}，审核已通过！";
        }
        $sql = "insert into tidings(`user_fs`, `user_js`, `title`, `content`, `object_id`, `object_type`, `type`, `create_time`)
                        values (0, {$find_spu[0]['user_cj']}, 'SPU审核', '{$content}', {$data['spu_id']}, 2, 1, now())";
        db::insert($sql);
        */

        return 1;
    }

    /**
     * 编辑spu
     * @param Id
     */
    public function spu_update($data)
    {
        $set = "";
        if (!empty($data['loop_time'])) {
            $data['loop_time'] = implode(',', $data['loop_time']);
        }
        $field_arr = array('state', 'user_cl', 'handle_time', 'handle_desc');
        foreach ($data as $k => $v) {
            if (in_array($k, $field_arr)) {
                $set .= ",`{$k}`='{$v}'";
            }
        }
        if (empty($set)) {
            return '修改数据为空';
        }
        $set = substr($set, 1);

        $sql = "update `spu`
				set {$set}
				where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '编辑失败';
        }
    }

////////////////////// sku列表

    /**
     * sku列表--数据
     * @param platform_id 平台id
     * @param type_id_1 大类
     * @param type_id_2 二类
     * @param type_id_3 三类
     * @param title 标题
     * @param spu spu编码
     * @param sku sku编码
     */
    public function sku_list($data)
    {
        $where = "spu.state=5";
        //$where = "1=1";
        //title sku标题
        if (!empty($data['sku_title'])) {
            $where .= " and sku.`title` like '%{$data['sku_title']}%'";
        }
        // user_kf_name 开发人
        if (!empty($data['user_kf_name'])) {
            $where .= " and u.`account` like '%{$data['user_kf_name']}%'";
        }
        // spu spu编码
        if (!empty($data['spu'])) {
            $where .= " and spu.`spu`='{$data['spu']}'";
        }
        // platform_id 平台id
        if (!empty($data['platform_id'])) {
            $where .= " and spu.`platform_id`={$data['platform_id']}";
        }
        // type_id_1 大类
        if (!empty($data['type_id_1'])) {
            $where .= " and spu.`type_id_1`={$data['type_id_1']}";
        }
        // type_id_2 二类
        if (!empty($data['type_id_2'])) {
            $where .= " and spu.`type_id_2`={$data['type_id_2']}";
        }
        // type_id_3 三类
        if (!empty($data['type_id_3'])) {
            $where .= " and spu.`type_id_3`={$data['type_id_3']}";
        }
        // sku sku编码
        if (!empty($data['sku'])) {
            $where .= " and sku.`sku`='{$data['sku']}'";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS sku.Id, sku.spu_id, sku.weight_j, sku.weight_m, sku.purchase_price, spu.spu, spu.level,  spu.number_qd, spu.day_cg, spu.is_spotgoods, spu.is_mode, spu.is_imitation, sku.sku, spu.supplier_id, sku.img_zt, sku.title, s.name as supplier_name, spu.user_kf,
					(select `account` from users where `Id`=spu.user_kf) as name_kf
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id
			    left join suppliers s on s.Id = spu.supplier_id
			    inner join users u on u.Id = spu.user_kf
				where {$where}
				order by sku.Id desc {$limit}";
//		return $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        $return['list'] = $list;
        return $return;
    }

    /**
     * sku导出
     * @param sku_ids sku id 字符串  1,2,3
     * @param platform_id 平台id
     * @param type_id_1 大类
     * @param type_id_2 二类
     * @param type_id_3 三类
     * @param sku_title sku标题
     * @param sku sku编码
     * @param spu spu编码
     */
    public function sku_export($data)
    {
        $where = "1=1";

        if (!empty($data['sku_ids'])) {
            // sku_ids sku id
            $where .= " and sku.Id in ({$data['sku_ids']})";
        } else {
            // sku_title sku标题
            if (!empty($data['sku_title'])) {
                $where .= " and sku.`title` like '%{$data['sku_title']}%'";
            }
            // sku sku编码
            if (!empty($data['sku'])) {
                $where .= " and sku.`sku` like '%{$data['sku']}%'";
            }
            // spu spu编码
            if (!empty($data['spu'])) {
                $where .= " and spu.`spu` like '%{$data['spu']}%'";
            }
            // platform_id 平台id
            if (!empty($data['platform_id'])) {
                $where .= " and spu.`platform_id`={$data['platform_id']}";
            }
            // type_id_1 大类
            if (!empty($data['type_id_1'])) {
                $where .= " and spu.`type_id_1`={$data['type_id_1']}";
            }
            // type_id_2 二类
            if (!empty($data['type_id_2'])) {
                $where .= " and spu.`type_id_2`={$data['type_id_2']}";
            }
            // type_id_3 三类
            if (!empty($data['type_id_3'])) {
                $where .= " and spu.`type_id_3`={$data['type_id_3']}";
            }
            //create_time 创建时间
            /*if (!empty($data['create_time'])) {
                $sel_time = explode(' - ',$data['create_time']);
                $sel_time[1] = $sel_time[1].' 23:59:59';
                $where .= " and e.create_time>='{$sel_time[0]}' and e.create_time<='{$sel_time[1]}'";
            }*/
        }

/*        $sql = "select spu.*,sku.*,spu.*, sku.title as sku_title,
                    sku.purchase_price as purchase_price_sku,
					sku.weight_j as weight_j_sku, sku.weight_m as weight_m_sku,spu.weight_j as weight_j,
					(select `name_yw` from spu_config where `Id`= sku.color_id) as color_name_yw,
					(select `identifying` from spu_config where `Id`= sku.size_id) as size_identifying,
					(select `name` from suppliers where `Id`= sup.supplier_id) as supplier_name,
					(select `account` from users where `Id`= spu.user_kf) as user_name_kf,
					(select `account` from users where `Id`= spu.user_kf) as user_name_zc,
					if(spu.user_cg!=0, (select `account` from users where `Id`= spu.user_cg), '') as user_name_cg
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id
				left join spu_supply sup on sup.spu_id = spu.Id
				where {$where}
				order by sku.id desc";*/

       /* $sql = "select sku.title,sku.img_info,sku.weight_m,sku.weight_j,sku.sku,sku.img_zt,spu.title_en,spu.spu,spu.packing_size_c,spu.packing_size_k,spu.packing_size_g,
                    spu.is_imitation,spu.is_mode,spu.is_spotgoods,spu.purchase_url_1,spu.day_sc,spu.day_ys,spu.day_rk,spu.day_cg,spu.supplier_hh, sku.title as sku_title,
                    sku.purchase_price as purchase_price_sku,sup.purchase_url_1 as purchase_url_supply,
					sku.weight_j as weight_j_sku, sku.weight_m as weight_m_sku,spu.weight_j as weight_j,
					(select `name_yw` from spu_config where `Id`= sku.color_id) as color_name_yw,
					(select `identifying` from spu_config where `Id`= sku.size_id) as size_identifying,
					(select `name` from suppliers where `Id`= sup.supplier_id) as supplier_name,
					(select `account` from users where `Id`= spu.user_kf) as user_name_kf,
					(select `account` from users where `Id`= spu.user_kf) as user_name_zc,
					if(spu.user_cg!=0, (select `account` from users where `Id`= spu.user_cg), '') as user_name_cg
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id   
				left join spu_supply sup on sup.spu_id = spu.Id
				where {$where}
				order by sku.id desc";*/

        $sql = "select sku.title,sku.img_info,sku.weight_m,sku.weight_j,sku.sku,sku.img_zt,spu.title_en,spu.spu,spu.packing_size_c,spu.packing_size_k,spu.packing_size_g,
                    spu.is_imitation,spu.is_mode,spu.is_spotgoods,spu.day_sc,spu.day_ys,spu.day_rk,spu.day_cg,spu.supplier_hh, sku.title as sku_title,
                    sku.purchase_price as purchase_price_sku, sup.purchase_url_1, 
					sku.weight_j as weight_j_sku, sku.weight_m as weight_m_sku,spu.weight_j as weight_j,
					(select `name_yw` from spu_config where `Id`= sku.color_id) as color_name_yw,
					(select `identifying` from spu_config where `Id`= sku.size_id) as size_identifying,
					(select `name` from suppliers where `Id`= sup.supplier_id) as supplier_name,
					(select `account` from users where `Id`= spu.user_kf) as user_name_kf,
					(select `account` from users where `Id`= spu.user_kf) as user_name_zc,
					if(spu.user_cg!=0, (select `account` from users where `Id`= spu.user_cg), '') as user_name_cg
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id   
				left join spu_supply sup on sup.spu_id = spu.Id
				where {$where}
				order by sku.id desc";



        $list = json_decode(json_encode(db::select($sql)), true);
//        echo "<pre>";
        ////处理数据
        foreach ($list as $ka => $va) {
            //var_dump($va);die;
            $list[$ka]['product_sku'] = '';
            $list[$ka]['product_ly'] = '开发采集';
            $list[$ka]['development_type'] = '现货直采';
            $list[$ka]['img_ly'] = '供应商提供';
            $list[$ka]['product_lbyw'] = '';
            $list[$ka]['product_lbzw'] = '';
            $list[$ka]['product_bgyw'] = '';
            $list[$ka]['product_bgzw'] = '';
            $list[$ka]['clearance_price'] = 1;
            $list[$ka]['clearance_unit'] = 'PCS';

            $list[$ka]['pcs'] = '';
            $list[$ka]['box_bzc'] = '';
            $list[$ka]['box_bzk'] = '';
            $list[$ka]['box_bzg'] = '';
            $list[$ka]['supplier_type'] = '网络采购';
            $list[$ka]['cost_jg'] = '';
            $list[$ka]['cost_qt'] = '';
            $list[$ka]['freight_cg'] = '';
            $list[$ka]['unit'] = 'PCS';
            $list[$ka]['unit_num'] = '';
            $list[$ka]['packing_c'] = $va['packing_size_c'];
            $list[$ka]['packing_k'] = $va['packing_size_k'];
            $list[$ka]['packing_g'] = $va['packing_size_g'];
            $list[$ka]['weight_dg'] = $va['weight_m_sku']*1000+10;
            //is_imitation 是否仿牌：1.是，2.否
            if ($va['is_imitation'] == '1') {
                $list[$ka]['is_imitation'] = '仿牌';
            } else if ($va['is_imitation'] == '2') {
                $list[$ka]['is_imitation'] = '非仿牌';
            }
            // productstate 属性
            if (!empty($va['productstate_id'])) {
                $productstate_id = explode(',', $va['productstate_id']);
                $sql = "select `name`
						from spu_config
						where `Id`={$productstate_id[0]}
						limit 1";
                $find = json_decode(json_encode(db::select($sql)), true);
                $list[$ka]['productstate'] = $find[0]['name'];
            } else {
                $list[$ka]['productstate'] = '';
            }
            $list[$ka]['product_state'] = '正常';
            $list[$ka]['product_state_remarks'] = '';
//			$list[$ka]['user_cg'] = '';
            $list[$ka]['user_fz'] = '';
            $list[$ka]['user_bj'] = '';
            $list[$ka]['user_cpcl'] = '';
            $list[$ka]['warehouse_mr'] = '';
            $list[$ka]['product_name_yw'] = '';
            $list[$ka]['material_bg'] = '';
            $list[$ka]['percentage_tsl'] = '';
            $list[$ka]['customs_no'] = '';
            $list[$ka]['is_customs_no'] = '';
            $list[$ka]['product_word'] = '';
            $list[$ka]['product_word_1'] = '';
            $list[$ka]['product_word_2'] = '';
            $list[$ka]['product_word_3'] = '';
            $list[$ka]['product_word_4'] = '';
            $list[$ka]['product_word_5'] = '';
            $list[$ka]['product_jyms'] = '';
            $list[$ka]['product_feature_1'] = '';
            $list[$ka]['product_feature_2'] = '';
            $list[$ka]['product_feature_3'] = '';
            $list[$ka]['product_feature_4'] = '';
            $list[$ka]['product_feature_5'] = '';
            $list[$ka]['product_ms'] = '';
            $list[$ka]['url_ck'] = '';
            $list[$ka]['product_bzqd'] = '';
            $list[$ka]['brand_name'] = '';
            $list[$ka]['price_my'] = '';
            // 图片
            $img_info = explode(',', $va['img_info']);
            $list[$ka]['product_qttp1'] = (!empty($img_info[0])) ? $img_info[0] : '';
            $list[$ka]['product_qttp2'] = (!empty($img_info[1])) ? $img_info[1] : '';
            $list[$ka]['product_qttp3'] = (!empty($img_info[2])) ? $img_info[2] : '';
            $list[$ka]['product_qttp4'] = (!empty($img_info[3])) ? $img_info[3] : '';
            $list[$ka]['product_qttp5'] = (!empty($img_info[4])) ? $img_info[4] : '';
            $list[$ka]['product_qttp6'] = (!empty($img_info[5])) ? $img_info[5] : '';
            $list[$ka]['product_qttp7'] = (!empty($img_info[6])) ? $img_info[6] : '';
            $list[$ka]['product_qttp8'] = (!empty($img_info[7])) ? $img_info[7] : '';
            $list[$ka]['product_qttp9'] = (!empty($img_info[8])) ? $img_info[8] : '';

            $list[$ka]['plug_qd'] = '';
            $list[$ka]['plug_gg'] = '';
            $list[$ka]['plug_ggbt'] = '';
            $list[$ka]['product_yt'] = '';
            $list[$ka]['remarks_kf'] = '';
            $list[$ka]['remarks_bj'] = '';
            $list[$ka]['remarks_zj'] = '';
            $list[$ka]['remarks_cgsh'] = '';
            $list[$ka]['model_gg'] = '';
            $list[$ka]['product_type'] = '';
            $list[$ka]['time_csqs'] = '';
            $list[$ka]['time_csjs'] = '';
            $list[$ka]['product_cg_sku'] = '';
            $list[$ka]['create_zd_time'] = '';
            $list[$ka]['is_photograph'] = '';
            $list[$ka]['remarks_fhdb'] = '';
            $list[$ka]['product_zxmz'] = '';
            $list[$ka]['product_zxjz'] = '';
            $list[$ka]['url_ozbg'] = '';
            $list[$ka]['time_dh'] = '';
            $list[$ka]['time_tc'] = '';
            $list[$ka]['number_qp'] = '';
            $list[$ka]['weight_m_sku'] = $va['weight_m_sku']*1000;
            $list[$ka]['weight_j_sku'] = $va['weight_j']*1000;
            $list[$ka]['weight_j'] = $va['weight_j']*1000;
            $list[$ka]['weight_m'] = $va['weight_m']*1000;
            $list[$ka]['purchase_url_1'] = empty($va['purchase_url_1'])?'':$va['purchase_url_1'];

        }
//		return $list;
        $title = array(
            'product_sku' => '产品SKU',
            'sku' => '自定义SKU',
            'color_name_yw' => '产品颜色英文',
            'size_identifying' => '产品尺码英文',
            'spu' => '母体变体',
            'product_ly' => '产品来源',
            'development_type' => '开发类型',
            'img_ly' => '图片来源',
            'product_lbyw' => '产品英文类别名',
            'product_lbzw' => '产品中文类别名',
            'sku_title' => '产品中文名',
            'product_bgyw' => '产品报关英文名',
            'product_bgzw' => '产品报关中文名',
            'clearance_price' => '报关价',
            'clearance_unit' => '报关单位',
            'pcs' => '每箱PCS数量',
            'packing_c' => '产品尺寸长（CM）',
            'packing_k' => '产品尺寸宽（CM）',
            'packing_g' => '产品尺寸高（CM）',
            'packing_size_c' => '产品包装尺寸长（CM）',
            'packing_size_k' => '产品包装尺寸宽（CM）',
            'packing_size_g' => '产品包装尺寸高（CM）',
            'box_bzc' => '外箱包装尺寸长（M）',
            'box_bzk' => '外箱包装尺寸宽（M）',
            'box_bzg' => '外箱包装尺寸高（M）',
            'purchase_price_sku' => '供货价(人民币)',
            'supplier_name' => '供应商名称',
            'supplier_type' => '供应商类型',
            'purchase_url_1' => '网络采购链接',
            'day_sc' => '生产天数',
            'day_ys' => '采购运输天数',
            'day_rk' => '入库天数',
            'cost_jg' => '加工费用',
            'cost_qt' => '其他费用',
            'freight_cg' => '采购运费',
            'unit' => '单位',
            'unit_num' => '单位数量',
            'weight_j_sku' => '净重(克)',
            'weight_m_sku' => '毛重(克)',
            'weight_dg' => '单个产品包裹重量(克)',
            'is_imitation' => '产品侵权风险',
            'productstate' => '产品物流属性',
            'product_state' => '产品状态',
            'product_state_remarks' => '产品状态备注',
            'user_name_cg' => '采购人员',
            'user_fz' => '负责人员',
            'user_bj' => '编辑人员',
            'user_cpcl' => '图片处理人员',
            'user_name_zc' => '知产人员',
            'warehouse_mr' => '默认本地发货仓库',
            'user_name_kf' => '开发人员',
            'product_name_yw' => '产品英文名',
            'material_bg' => '报关材质',
            'percentage_tsl' => '退税率',
            'customs_no' => '海关编码',
            'is_customs_no' => '是否审核海关编码',
            'product_word' => '产品关键词',
            'product_word_1' => '产品关键词1',
            'product_word_2' => '产品关键词2',
            'product_word_3' => '产品关键词3',
            'product_word_4' => '产品关键词4',
            'product_word_5' => '产品关键词5',
            'product_jyms' => '产品简要描述',
            'product_feature_1' => '产品特征1',
            'product_feature_2' => '产品特征2',
            'product_feature_3' => '产品特征3',
            'product_feature_4' => '产品特征4',
            'product_feature_5' => '产品特征5',
            'product_ms' => '产品描述',
            'url_ck' => '参考网站链接',
            'product_bzqd' => '产品包装清单',
            'brand_name' => '品牌名',
            'price_my' => '售价（美元）',
            'supplier_hh' => '供应商产品编码',
            'img_zt' => '产品主图',
            'product_qttp1' => '产品其他图片1',
            'product_qttp2' => '产品其他图片2',
            'product_qttp3' => '产品其他图片3',
            'product_qttp4' => '产品其他图片4',
            'product_qttp5' => '产品其他图片5',
            'product_qttp6' => '产品其他图片6',
            'product_qttp7' => '产品其他图片7',
            'product_qttp8' => '产品其他图片8',
            'product_qttp9' => '产品其他图片9',
            'plug_qd' => '强电插头',
            'plug_gg' => '插头规格',
            'plug_ggbt' => '插头规格作为产品标题',
            'product_yt' => '产品用途',
            'remarks_kf' => '开发备注',
            'remarks_bj' => '编辑备注',
            'remarks_zj' => '质检备注',
            'remarks_cgsh' => '采购收货备注',
            'model_gg' => '规格型号',
            'product_type' => '产品类型',
            'time_csqs' => '出售起始时间',
            'time_csjs' => '出售结束时间',
            'product_cg_sku' => '采购产品包材SKU',
            'create_zd_time' => '采购产品包材自定义SKU',
            'is_photograph' => '是否需要拍照',
            'remarks_fhdb' => '发货打包备注',
            'product_zxmz' => '整箱产品毛重(kg)',
            'product_zxjz' => '整箱产品净重(kg)',
            'url_ozbg' => '欧洲报关链接',
            'time_dh' => '到货日期',
            'time_tc' => '停产日期',
            'number_qp' => '起批量',
        );
//        echo "<pre>";
//var_dump($list);die;
        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new \PHPExcel();
        $PHPExcel_Style_Alignment = new\PHPExcel_Style_Alignment;

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ");
        // 设置excel标题
        $index = 0;
        foreach ($title as $k => $v) {
            $objPHPExcel->getActiveSheet()->getStyle('A1:AU1')->getFont()->setBold(true);//第一行是否加粗
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);    //第一行行高
            $objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(60);
            $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);
            $index++;
        }
        //var_dump($list);die;
        foreach ($list as $k => $v) {
            $num = $k + 2;
            //字体大小
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getFont()
                ->setSize(10);
            //设置水平居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置垂直居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //自动换行
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setWrapText(true);

            // 重置列索引起始位
            $i = 0;
            foreach ($title as $key => $value) {
                $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue($cellName[$i] . $num, $v[$key]);
                $i++;
            }
        }
        $objPHPExcel->getActiveSheet()->setTitle('work');
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="SKU列表.xls"');
        header('Cache-Control: max-age=1');
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
        exit();
    }

    /**
     * 编辑sku
     * @param Id
     */
    public function sku_update($data)
    {
        $set = "";
        $arr = array('title', 'sku_log', 'purchase_price', 'weight_j', 'weight_m');
        foreach ($data as $k => $v) {
            if (!empty($v)) {
                if (in_array($k, $arr)) {
                    $set .= ",s.`{$k}`=" . (is_numeric($v) ? "{$v}" : "'{$v}'");
                }
            }
        }

        if (empty($set)) {
            return '修改数据为空';
        }
        $set = substr($set, 1);

        $sql = "update spu_sku s
				set {$set}
				where s.Id = {$data['Id']}";
        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '修改失败';
        }
    }

    /**
     * 删除sku
     * @param Id
     */
    public function sku_del($data)
    {
        $sql = "delete
				from `spu_sku`
				where `Id`={$data['Id']}";
        $delete = db::delete($sql);
        if ($delete) {
            return 1;
        } else {
            return '删除失败';
        }
    }

    /**
     * lazada平台品牌
     *
     */
    public function brand_lzd($data)
    {
        $platform_id = $data['platform_id'];
        //刷新品牌
        if (isset($data['reload'])) {
            //判断店铺是否授权
            $store_id = $data['store_id'];
            $sql = "select * from shop where Id={$store_id}";
            $shop = json_decode(json_encode(db::select($sql)), true);
            if (empty($shop[0]['access_token'])) {
                return '该店铺暂未授权';
            }
            /*  $sql = "select * from shop";
            $shop = json_decode(json_encode(db::select($sql)),true);*/
            $arr = json_decode($shop[0]['app_data'], true);
            $app_key = $arr['app_key'];
            $app_secret = $arr['app_secret'];
            $arr['access_token'] = $shop[0]['access_token'];
            $arr['shop_id'] = $shop[0]['Id'];
            //请求lazada平台接口，获取品牌
            $call_wish = new \App\Libs\platformApi\Lazada($arr);
            $resData = $call_wish->brand_get($data);
            if ($resData['code'] == 0) {
                //删除原有数据
                $sql = "Delete from platform_brand where platform_id={$platform_id}";
                $res = DB::delete($sql);
                $brandData = $resData['data']['module'];
                foreach ($brandData as $key => $value) {
                    $name = $value['name'];
                    $global_identifier = $value['global_identifier'];
                    $name_en = $value['name_en'];
                    $brand_id = $value['brand_id'];
                    $res = DB::table('platform_brand')->insert(['name' => $name, 'global_identifier' => $global_identifier, 'name_en' => $name_en, 'brand_id' => $brand_id, 'platform_id' => $platform_id]);
                }
            }

        }
        $sql = "select * from platform_brand where platform_id={$platform_id}";
        $brand = json_decode(json_encode(db::select($sql)), true);
        $return['list'] = $brand;
        return $return;
    }

    /**
     * 上传spu到lazada
     */
    public function create_lzd($data)
    {
	    //// rabbitmq
	    $rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_3', 'queue_3', 'key_3');
			
	    foreach ($data['store_id'] as $k=>$v){
		    //消息内容
		    $msg_data = $data;
		    $msg_data['time'] = date('Y-m-d H:i:s');
		    $msg_data['time_zx'] = time();// 执行时间
		    $msg_data['store_id'] = $v;
		    //// 发送消息
		    $rabbitmq->send_message($msg_data);
	    }
		
	    //// 关闭连接
	    $rabbitmq->close_connetct();
	
	    return 1;
    }
	
	/**
	 * 上传spu到lazada
	 */
	public function product_get_lazada($data)
	{
		/// 获取产品分类id
		$category_id = $data['category_id'];
		$primary_category = $category_id[(count($category_id) - 1)];
		
		//// 获取店铺信息
		$sql = "select *
	                 from shop
	                 where Id={$data['store_id']}
	                 limit 1";
		$shop_find = json_decode(json_encode(db::select($sql)), true);
		if (empty($shop_find)) {
			return '店铺不存在';
		} else if ($shop_find[0]['authorization_state'] == 1) {
			return '该店铺暂未授权';
		}
		
		$sku_list = implode(",", array_column($data['sku'], 'sku'));
		
		//// 实例化 lazada 类
		$arr = json_decode($shop_find[0]['app_data'], true);
		$arr['access_token'] = $shop_find[0]['access_token'];
		$arr['shop_id'] = $shop_find[0]['Id'];
		
		$call_lazada = new \App\Libs\platformApi\Lazada($arr);
		
		//// 上传产品
		// 产品差异--标题、图片、价格（1块上下浮动）
		// 标题   随机打乱标题
		$title_rand = explode(",", $data['spu']['title_rand']);
		$title_rand[] = $data['spu']['title_en'];
		shuffle($title_rand);// 随机打乱数组
		$data['spu']['name'] = implode(" ", $title_rand);
		
		//价格（1块上下浮动）
		$price_bd = rand(-100, 100) / 100;
		foreach ($data['sku'] as $k=>$v){
			//图片 随机打乱位置
			shuffle($data['sku'][$k]['image']);// 随机打乱数组
			//价格
			$data['sku'][$k]['price'] = $v['price'] + $price_bd;
			if(isset($v['special_price'])){
				$data['sku'][$k]['special_price'] = $v['special_price'] + $price_bd;// 特价 可选
			}
//			$data['sku'][$k]['sku'] = time() .'_'. rand(10000, 99999). rand(10000, 99999);
		}
		
		//国家
		$country = $data['country'];
		if(in_array('all', $country)){
			$country = array('Philippines', 'Thailand', 'Singapore', 'Malaysia', 'Vietnam', 'Indonesia');
		}
		
		$arr = $data;
		$arr['spu']['primary_category'] = $primary_category;
		foreach ($country as $k=>$v){
			$arr['country'] = $v;
			$product_add = $call_lazada->product_add($arr);
//			return $product_add;
			if ($product_add['code'] != 0) {
				//// 新增产品上传记录
				$sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `data_jkfh`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['spu']}', 2, '{$product_add['detail'][0]['message']}', '{$sku_list}', '{$data['time']}', now())";
				db::insert($sql);
				return $product_add['detail'][0]['message'];
			}
		}
		
		//// 新增产品上传记录
		$sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['spu']}', 3, '{$sku_list}', '{$data['time']}', now())";
		db::insert($sql);
		
		return 1;
	}


    public function spu_store($data)
    {
        $sql = "select * from platform";
        $platform = json_decode(json_encode(db::select($sql)), true);
        foreach ($platform as $key => $value) {
            $platformId = $value['Id'];
            $sql = "select * from shop ";
            $shop = json_decode(json_encode(db::select($sql)), true);
            foreach ($shop as $k => $v) {
                if ($v['platform_id'] == $platformId) {
                    $value['shop'][$k] = $v;
                }

            }
            $list[] = $value;
        }
        $return['list'] = $list;
        //var_dump($list);die;
        return $return;
    }


    //获取lzd字段数据
    public function data_lzd($data)
    {
        $spu_id = $data['spu_id'];
        $platform_id = $data['platform_id'];
        $sql = "select SQL_CALC_FOUND_ROWS s.*
				from `spu` s
				left join platform p on p.Id = s.platform_id
				where s.Id={$spu_id}";
        $spu = json_decode(json_encode(db::select($sql)), true);
        $sql = "select SQL_CALC_FOUND_ROWS spu.spu,spu.weight_m as package_weight,spu.packing_size_c as package_length,spu.packing_size_k as package_width,spu.packing_size_g as package_height,spr.price_sc as market_price,spr.price_jy as shop_price ,sku.img_info as image,sco.name_yw as color_family,scf.identifying as style_quantity,scg.identifying as size, sku.sku as seller_sku,sku.purchase_price as purchase_price,sku.weight_m
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id
			    left join suppliers s on s.Id = spu.supplier_id
			    left join spu_price spr on spu.Id=spr.spu_id and spr.platform_id={$platform_id}
			    left join spu_config sco on sco.Id = sku.color_id
			    left join spu_config scf on scf.Id = sku.style_id
			    left join spu_config scg on scg.Id = sku.size_id
			    inner join users u on u.Id = spu.user_kf
				where spu.Id={$spu_id}";// and spu.platform_id={$platform_id}
        $sku = json_decode(json_encode(db::select($sql)), true);
        //var_dump($sku);die;//left join spu_config sco on sco.Id = sku.color_id
	    $list['spu'] = $spu[0]['spu'];
	    $list['title_en'] = $spu[0]['title_en'];
        $list['title_rand'] = $spu[0]['title_rand'];
        $title_rand =str_replace(',',' ',$spu[0]['title_rand']);
        $list['name'] = $spu[0]['title_en'].' '.$title_rand;
        $list['venture'] = '';
        $list['short_description'] = '';
        $list['description'] = $spu[0]['parameter_info'];
        $list['brand'] = '';
        $list['model'] = $spu[0]['model'];
        /*$list['package_length'] = $spu[0]['packing_size_c'];
        $list['package_height'] = $spu[0]['packing_size_k'];
        $list['package_weight'] = $spu[0]['packing_size_g'];
        $list['package_width'] = $spu[0]['weight_j'];*/
        $list['package_content'] = '';
        $return['spu'] = $list;
        $return['sku'] = $sku;
        return $return;


    }
	
    
    public function category_lzd($data)
    {
        $platform_id = $data['platform_id'];
        $store_id = $data['store_id'];
		
	    $sql = "select s.*
	                from shop s
	                where s.Id={$data['store_id']}
	                limit 1";
	    $shop = json_decode(json_encode(db::select($sql)), true);
	    if(empty($shop)){
		    return '获取店铺数据失败';
	    }else if(empty($shop[0]['app_data'])){
		    return '授权数据为空';
	    }
	    
	    //// 实例化 lazada 类
	    $arr = json_decode($shop[0]['app_data'], true);
	    $arr['access_token'] = $shop[0]['access_token'];
	    $call_lazada = new \App\Libs\platformApi\Lazada($arr);
		// 获取平台分类
	    $category_get = $call_lazada->category_get();
	    if ($category_get['code'] != 0) {
		    return $category_get;
	    }
	    
	    //// 删除分类
	    $sql = "delete
	                from category
	                where platform_id = {$data['platform_id']}";
	    db::delete($sql);
		
	    //// 存储数据
        $cate = $this->cate($category_get['data'], 0, $data['platform_id']);
        
        //获取刷新后的主营分类
        $sql = "select * from shop where Id={$store_id} and platform_id={$platform_id}";
        $shop = json_decode(json_encode(db::select($sql)), true);
        $main_classification = $shop[0]['main_classification'];
        //当前店铺所有主营分类
        if ($main_classification == 'all') {
            $sql = "select * from category where platform_id={$platform_id}";
            $category_data = json_decode(json_encode(db::select($sql)), true);
            foreach ($category_data as $key => $value) {
                $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                $res = json_decode(json_encode(db::select($sql)), true);
                if (empty($res)) {
                    $value['last'] = 1;
                } else {
                    $value['last'] = 2;
                }
                $list[] = $value;
                //var_dump($res);
            }
        } else {
            $sql = "select * from category where category_id in({$main_classification}) and platform_id={$platform_id}";
            $category_data = json_decode(json_encode(db::select($sql)), true);
            foreach ($category_data as $key => $value) {
                $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                $res = json_decode(json_encode(db::select($sql)), true);
                if (empty($res)) {
                    $value['last'] = 1;
                } else {
                    $value['last'] = 2;
                }
                $list[] = $value;
                //var_dump($res);
            }
        }
        $return['list'] = $list;
        return $return;

    }

    //获取分类(lazada,vova)
    public function category_main($data)
    {
        $platform_id = $data['platform_id'];
        //判断是否有分类表Id，没有为查找第一层
        if (isset($data['classify_id'])) {
            $pid = $data['classify_id'];
            $sql = "select * from category where pid={$pid} and platform_id={$platform_id}";
            $category = json_decode(json_encode(db::select($sql)), true);
            if (!empty($category)) {
                foreach ($category as $key => $value) {
                    $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                    $res = json_decode(json_encode(db::select($sql)), true);
                    if (empty($res)) {
                        $value['last'] = 1;
                    } else {
                        $value['last'] = 2;
                    }
                    $list[] = $value;
                    //var_dump($res);
                }//die;
            } else {
                $list[0]['last'] = 1;
            }
        } else {
            $store_id = $data['store_id'];
            $sql = "select * from shop where Id={$store_id} and platform_id={$platform_id}";
            $shop = json_decode(json_encode(db::select($sql)), true);
            $main_classification = $shop[0]['main_classification'];
            //当前店铺所有主营分类
            if ($main_classification == 'all') {
                $sql = "select * from category where platform_id={$platform_id} and pid=0";
                $category_data = json_decode(json_encode(db::select($sql)), true);
                foreach ($category_data as $key => $value) {
                    $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                    $res = json_decode(json_encode(db::select($sql)), true);
                    if (empty($res)) {
                        $value['last'] = 1;
                    } else {
                        $value['last'] = 2;
                    }
                    $list[] = $value;
                    //var_dump($res);
                }
            } else {
                $sql = "select * from category where category_id in({$main_classification}) and platform_id={$platform_id}";
                $category_data = json_decode(json_encode(db::select($sql)), true);
                foreach ($category_data as $key => $value) {
                    $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                    $res = json_decode(json_encode(db::select($sql)), true);
                    if (empty($res)) {
                        $value['last'] = 1;
                    } else {
                        $value['last'] = 2;
                    }
                    $list[] = $value;
                    //var_dump($res);
                }
            }

        }

        //var_dump($list);die;
        $return['list'] = $list;
        return $return;
    }

    //获取店铺分类
    public function main_classification($data)
    {
        $platform_id = $data['platform_id'];
        $store_id = $data['store_id'];
        $sql = "select * from shop where Id={$store_id}";
        $shop = json_decode(json_encode(db::select($sql)), true);
//        var_dump($shop);die;
        $main_classification = $shop[0]['main_classification'];
        if ($main_classification == 'all') {
            $sql = "select * from category where platform_id={$platform_id}"; //and pid=0
            $category = json_decode(json_encode(db::select($sql)), true);
//            foreach($category as $key=>$value){
//                $pid = $value['Id'];
//                $cate_arr[] = $this->cate_arr($platform_id,$store_id,$pid,$value);
//            }
            $pid = 0;
            $list = array();
            $cate_arr = $this->cate_arr($category, $pid);
            //var_dump($value);

            //var_dump($cate_arr);die;
        } else {
            $sql = "select * from category where platform_id={$platform_id} and category_id in({$main_classification})"; //and pid=0
            $category_find = json_decode(json_encode(db::select($sql)), true);
            foreach ($category_find as $key => $value) {
                $pid[] = $value['Id'];
            }
            $sql = "select * from category where platform_id={$platform_id}"; //and pid=0
            //var_dump($sql);die;
            $category = json_decode(json_encode(db::select($sql)), true);
            //foreach ($category as $key=>$value){
            //$pid = $value['Id'];
            //$pid = 0;
            //$main_classification =
            $list = array();
            $parent_arr = $this->parent_arr($category, $pid, $category_find);
            //$parent_arr = $this->parent_arr($value,$pid);
            // }
            var_dump($parent_arr);
            die;
        }

    }


    //public function parent_arr($data,$pid){
    public function parent_arr($category, $pid, $list)
    {
        foreach ($category as $key => $value) {
            if (is_array($pid)) {
                foreach ($pid as $ke => $val) {
                    //if($value['category_id']==$val){
                    if ($val == $value['pid']) {
                        //var_dump($val);
                        $pid = $value['Id'];
                        $list = array_merge($list, $value);
                        //var_dump($value);
                        //$main_classification = '';
                        $this->parent_arr($category, $pid, $list);
                        //var_dump($list);
                    }
                }
            } else {
                if ($pid == $value['pid']) {
                    //var_dump($val);
                    $pid = $value['Id'];
                    $list = array_merge($list, $value);
                    //$main_classification = '';
                    $this->parent_arr($category, $pid, $list);
                    //var_dump($list);
                }
            }


        }
        var_dump($list);
        die;
    }

    //vova平台分类
    public function category_vova($data)
    {
        $platform_id = $data['platform_id'];
        $store_id = $data['store_id'];
        $sql = "select * from shop where Id={$store_id}";
        $shop = json_decode(json_encode(db::select($sql)), true);
        if (empty($shop[0]['access_token'])) {
            return '该店铺暂未授权';
        }
        $sql = "select * from category where platform_id={$platform_id}";
        $category = json_decode(json_encode(db::select($sql)), true);
        if (!empty($category[0])) {
            $sql = "delete from category where platform_id={$platform_id}";
            db::delete($sql);
        }
        $appData = json_decode($shop[0]['app_data'], true);
        $app_key = $appData['app_key'];
        $app_secret = $appData['app_secret'];
        //var_dump($app_key);die;
        $access_token = $shop[0]['access_token'];

        $http = "https://merchant.vova.com.hk/api/v1/product/getGoodsCategory?token={$access_token}";

        $vova = $this->curls($http);
        $vovaData = json_decode($vova, true);

        //var_dump($vovaData);die;

        $res = $vovaData['vova_category'];
        //var_dump('1');die;
        $cate = $this->cate($res, 0, $platform_id);
        //var_dump('11');die;
        $sql = "select * from shop where Id={$store_id} and platform_id={$platform_id}";
        $shop = json_decode(json_encode(db::select($sql)), true);
        $main_classification = $shop[0]['main_classification'];
        //当前店铺所有主营分类
        if ($main_classification == 'all') {
            $sql = "select * from category where platform_id={$platform_id} and pid=0";
            $category_data = json_decode(json_encode(db::select($sql)), true);
            foreach ($category_data as $key => $value) {
                $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                $res = json_decode(json_encode(db::select($sql)), true);
                if (empty($res)) {
                    $value['last'] = 1;
                } else {
                    $value['last'] = 2;
                }
                $list[] = $value;
                //var_dump($res);
            }
        } else {
            $sql = "select * from category where category_id in({$main_classification}) and platform_id={$platform_id}";
            $category_data = json_decode(json_encode(db::select($sql)), true);
            foreach ($category_data as $key => $value) {
                $sql = "select * from category where pid={$value['Id']} and platform_id={$platform_id}";
                $res = json_decode(json_encode(db::select($sql)), true);
                if (empty($res)) {
                    $value['last'] = 1;
                } else {
                    $value['last'] = 2;
                }
                $list[] = $value;
                //var_dump($res);
            }
        }


        $return['list'] = $list;
        return $return;
    }

    //获取vova字段数据
    public function data_vova($data)
    {
        $spu_id = $data['spu_id'];
        $platform_id = $data['platform_id'];
        $sql = "select SQL_CALC_FOUND_ROWS s.*,ssy.day_ys as day_ys
				from `spu` s
				left join platform p on p.Id = s.platform_id
				left join spu_supply ssy on ssy.spu_id = s.Id
				where s.Id={$spu_id}";
        $spu = json_decode(json_encode(db::select($sql)), true);
        $sql = "select SQL_CALC_FOUND_ROWS sku.Id, spu.spu,spr.price_sc as market_price,spr.price_jy as shop_price ,sku.img_info as extra_image_list,sco.name_yw as style_color,scf.identifying as style_quantity,scg.identifying as style_size,sku.img_info as extra_image, sku.sku as goods_sku,sku.purchase_price as purchase_price,sku.weight_m
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id
			    left join suppliers s on s.Id = spu.supplier_id
			    left join spu_price spr on spu.Id=spr.spu_id and spr.platform_id={$platform_id}
			    left join spu_config sco on sco.Id = sku.color_id
			    left join spu_config scf on scf.Id = sku.style_id
			    left join spu_config scg on scg.Id = sku.size_id
			    inner join users u on u.Id = spu.user_kf
				where spu.Id={$spu_id}";// and spu.platform_id={$platform_id}
        $sku = json_decode(json_encode(db::select($sql)), true);
        //var_dump($sku);die;
        $list['size_chart'] = json_decode($spu[0]['size_chart'],true);
        if(empty($list['size_chart'])){
            $size_chart = array();
            $size_chart[0]['Size'] = '';
            $list['size_chart'] = $size_chart;
        }
        $list['parent_sku'] = $spu[0]['spu'];
	    $list['title_en'] = $spu[0]['title_en'];
        $list['title_rand'] = $spu[0]['title_rand'];
        $title_rand =str_replace(',',' ',$spu[0]['title_rand']);
        $list['goods_name'] = $spu[0]['title_en'].' '.$title_rand;
        $list['goods_name_fr'] = '';
        $list['goods_name_de'] = '';
        $list['goods_name_es'] = '';
        $list['goods_name_it'] = '';
        $list['goods_description'] = $spu[0]['parameter_info'];
        $list['goods_description_fr'] = '';
        $list['goods_description_de'] = '';
        $list['goods_description_es'] = '';
        $list['goods_description_it'] = '';
        $list['shipping_weight'] = $spu[0]['weight_m'];
        $list['shipping_time'] = $spu[0]['day_ys'];
        $list['main_image'] = $spu[0]['main_img'];
        $list['extra_image_list'] = !empty($spu[0]['extra_img'])?explode(',',$spu[0]['extra_img']):array();
        $list['tags'] = $spu[0]['label'];
        $list['goods_brand'] = $spu[0]['brand'];
        $return['spu'] = $list;
        $return['sku'] = $sku;
        //var_dump($list);die;
        //  var_dump($return);die;
        return $return;


    }
	
	/*
	 * 产品上传--vova
	 * */
	public function create_vova($data)
	{
		//// rabbitmq
		$rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_3', 'queue_3', 'key_3');
		
		foreach ($data['store_id'] as $k=>$v){
			//消息内容
			$msg_data = $data;
			$msg_data['time'] = date('Y-m-d H:i:s');
			$msg_data['time_zx'] = time();// 执行时间
			$msg_data['store_id'] = $v;
			
			//// 发送消息
			$rabbitmq->send_message($msg_data);
		}
		
		//// 关闭连接
		$rabbitmq->close_connetct();
		
		return 1;
	}
    /*
	 * 产品上传--vova
	 * */
    public function product_get_vova($data)
    {
        //// 获取店铺信息
        $sql = "select *
                   from shop
                   where Id={$data['store_id']}
                   limit 1";
        $shop_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($shop_find)) {
            return '店铺不存在';
        } else if ($shop_find[0]['authorization_state'] == 1) {
            return '该店铺暂未授权';
        }
		
	    //// 实例化 vova 类
	    $arr = array(
		    'access_token' => $shop_find[0]['access_token']
	    );
	    $call_vova = new \App\Libs\platformApi\Vova($arr);
	
	    //// 上传产品
	    if(!empty($data['spu'])){
		    /// 获取产品分类id
		    $category_id = $data['category_id'];
		    $key = count($category_id) - 1;
		    $cate_id = $category_id[$key];
		    $sku_list = implode(",", array_column($data['sku'], 'sku'));
			
		    // 产品差异--标题、图片、价格（1块上下浮动）
		    // 标题   随机打乱标题
		    $title_rand = explode(",", $data['spu']['title_rand']);
		    $title_rand[] = $data['spu']['title_en'];
		    shuffle($title_rand);// 随机打乱数组
		    $data['spu']['goods_name'] = implode(" ", $title_rand);
		    //图片 随机打乱位置
		    shuffle($data['spu']['extra_image_list']);// 随机打乱数组
		    //价格（1块上下浮动）
		    $price_bd = rand(-100, 100) / 100;
		    foreach ($data['sku'] as $k=>$v){
			    // 价格
			    $data['sku'][$k]['shop_price'] = $v['shop_price'] + $price_bd;
			    $data['sku'][$k]['market_price'] = $v['market_price'] + $price_bd;
			    // sku 图片
//			    shuffle($data['sku'][$k]['extra_image']);
//			    $data['sku'][$k]['sku'] = time() .'_'. rand(10000, 99999). rand(10000, 99999);
		    }
//		    $data['spu']['parent_sku'] = 'test_18_1';
		    $arr = $data;
		    $arr['spu']['cat_id'] = $cate_id;
		    $product_add = $call_vova->product_add($arr);
//		    return $product_add;
		    $data_jkfh = json_encode($product_add);
		    if ($product_add['data']['code'] != '20000') {
			    //// 新增产品上传记录
			    $sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `data_jkfh`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['parent_sku']}', 2, '{$data_jkfh}', '{$sku_list}', '{$data['time']}', now())";
			    db::insert($sql);
			    return $product_add['data']['message'];
		    }
			
		    //// 新增产品上传记录
		    $sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `data_jkfh`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['parent_sku']}', 3, '{$data_jkfh}', '{$sku_list}', '{$data['time']}', now())";
		    db::insert($sql);
			
		    //// 上传剩余SKU
		    if (count($data['sku']) > 1) {
			    unset($data['sku'][0]);// 去除第一个
			    
			    $arr = array();
			    $arr['time_zx'] = time() + 60;// 执行时间
			    $arr['platform_id'] = $data['platform_id'];
			    $arr['store_id'] = $data['store_id'];
			    $arr['sale'] = $data['sale'];//是否上架：1.上架，2.不上架
			    $arr['parent_sku'] = $data['spu']['parent_sku'];//父sku
			    $arr['size_chart'] = !empty($data['size_chart']) ? $data['size_chart'] : array();// 尺码表
			    $arr['sku'] = $data['sku'];
			    return $arr;
		    }
	    }
		
	    //// 上传sku/尺码表/上架
	    if(empty($data['spu'])){
		    //// 获取商品
		    $arr = array();
		    $arr['search_parent_sku'] = $data['parent_sku'];
		    $product_get = $call_vova->product_get($arr);
//		    return $product_get;
		    if($product_get['page_arr']['totalPage'] == 0){
			    //// 无数据
			    $data['time_zx'] = time() + 60;//执行时间
			    return $data;
		    }
			
		    //// 尺码表
		    if(!empty($data['size_chart'])){
			    // 尺码表
			    $arr = array(
				    'product_id' => $product_get['product_list'][0]['product_id'],
				    'size_data' => $data['size_chart']
			    );
			    $size_vova = $call_vova->size_vova($arr);
			    if ($size_vova['execute_status'] == 'success') {
				    unset($data['size_chart']);
			    }
		    }
		
		    ///// 上传商品 SKU
		    if(!empty($data['sku'])){
			    foreach ($data['sku'] as $k=>$v){
				    $v['parent_sku'] = $data['parent_sku'];// 父sku
				    $product_sku_add = $call_vova->product_sku_add($v);
				    /*if ($product_sku_add['execute_status'] != 'success') {
					    var_dump($product_sku_add);
				    }*/
			    }
			    unset($data['sku']);
		    }
			
		    ///// 上架
		    if(!empty($data['sale']) && $data['sale']=='1'){
			    $enableSale = $call_vova->enableSale('', $product_get['product_list'][0]['product_id']);
			    if ($enableSale['execute_status'] != 'success') {
				    $data['time_zx'] = time() + 60*5;//执行时间
				    return $data;
			    }
		    }
		    
	    }
		
        return 1;
    }


    public function data_wish($data)
    {
        $spu_id = $data['spu_id'];
        $platform_id = $data['platform_id'];
        $sql = "select SQL_CALC_FOUND_ROWS s.*
					from `spu` s
					left join platform p on p.Id = s.platform_id
					where s.Id={$spu_id}";
        $spu = json_decode(json_encode(db::select($sql)), true);
        
        $sql = "select SQL_CALC_FOUND_ROWS spu.weight_j as weight,spu.packing_size_c as length,spu.packing_size_k as width,spu.packing_size_g as height,sku.img_info as extra_images,spu.day_ys as shipping_time,spu.spu,spr.price_jy as price,sku.img_info as extra_image_list,sco.name_yw as color,scf.identifying as style_quantity,scg.identifying as size,sku.img_info as main_image, sku.sku as sku,sku.purchase_price as purchase_price,sku.weight_m
				from `spu`
				inner join spu_sku sku on sku.spu_id = spu.Id
			    left join suppliers s on s.Id = spu.supplier_id
			    left join spu_price spr on spu.Id=spr.spu_id and spr.platform_id={$platform_id}
			    left join spu_config sco on sco.Id = sku.color_id
			    left join spu_config scf on scf.Id = sku.style_id
			    left join spu_config scg on scg.Id = sku.size_id
			    inner join users u on u.Id = spu.user_kf
				where spu.Id={$spu_id}";// and spu.platform_id={$platform_id}
        $sku = json_decode(json_encode(db::select($sql)), true);
        //var_dump($sku);die;
        /*$title_rand =explode(',',$spu[0]['title_rand']);
        $key = array_rand($title_rand);*/
	    $list['title_en'] = $spu[0]['title_en'];
        $list['title_rand'] = $spu[0]['title_rand'];
        $title_rand =str_replace(',',' ',$spu[0]['title_rand']);
        $list['parent_sku'] = $spu[0]['spu'];
        $list['name'] = $spu[0]['title_en'].' '.$title_rand;
        $list['description'] = $spu[0]['parameter_info'];
        $list['shipping_weight'] = $spu[0]['weight_m'];
        $list['tags'] = $spu[0]['label'];
        //$list['goods_brand'] = '';
        //$list['localized_price'] = '';//本国货币变动价格
        $list['shipping'] = '';//运费
        $list['localized_shipping'] = '';
        $list['localized_currency_code'] = '';
        $list['country_shipping_prices'] = '';
        //$list['requested_product_brand_id'] = '';
        $list['landing_page_url'] = '';
        $list['extra_images'] = $spu[0]['extra_img'];//$sku[0]['extra_images']
        $list['clean_image'] = '';
        $list['max_quantity'] = '';
        $list['upc'] = '';
        $list['inset'] = '';
        $list['demo_video_asset_url'] = '';
        $return['spu'] = $list;
        $return['sku'] = $sku;
        //var_dump($return);die;
        return $return;


    }

    /*
     * 上传产品--wish
     * */
    public function create_wish($data)
    {
	    //// rabbitmq
	    $rabbitmq = new \App\Libs\wrapper\Rabbitmq('exchange_3', 'queue_3', 'key_3');
	    
	    foreach ($data['store_id'] as $k=>$v){
	    	//消息内容
		    $msg_data = $data;
		    $msg_data['time'] = date('Y-m-d H:i:s');
			$msg_data['time_zx'] = time();// 执行时间
		    $msg_data['store_id'] = $v;
			
		    //// 发送消息
		    $rabbitmq->send_message($msg_data);
	    }
	
	    //// 关闭连接
	    $rabbitmq->close_connetct();
	    
	    return 1;
    }
	
	/*
	 * 上传产品--wish
	 * */
	public function product_upload_wish($data)
	{
		// 获取店铺信息
		$sql = "select *
					from shop
					where Id={$data['store_id']}
					limit 1";
		$shop_find = json_decode(json_encode(db::select($sql)), true);
		if (empty($shop_find)) {
			return '店铺不存在';
		} else if ($shop_find[0]['authorization_state'] == 1) {
			return '该店铺未授权';
		}
		
		$sku_list = implode(",", array_column($data['sku'], 'sku'));
		
		//// 实例化 wish 类
		$arr = json_decode($shop_find[0]['app_data'], true);
		$arr['access_token'] = $shop_find[0]['access_token'];
		$arr['shop_id'] = $shop_find[0]['Id'];
		$call_wish = new \App\Libs\platformApi\Wish($arr);
		
//		$data['spu']['parent_sku'] = 'test_18_1';
		
		// 上传商品
		// 产品差异--标题、图片、价格（1块上下浮动）
		// 标题   随机打乱标题
		$title_rand = explode(",", $data['spu']['title_rand']);
		$title_rand[] = $data['spu']['title_en'];
		shuffle($title_rand);// 随机打乱数组
		$data['spu']['name'] = implode(" ", $title_rand);
		//图片 随机打乱位置
		$extra_images = explode("|", $data['spu']['extra_images']);
		shuffle($extra_images);// 随机打乱数组
		$data['spu']['extra_images'] = implode("|", $extra_images);
		//价格（1块上下浮动）
		$price_bd = rand(-100, 100) / 100;
		foreach ($data['sku'] as $k=>$v){
			$data['sku'][$k]['price'] = $v['price'] + $price_bd;
			$data['sku'][$k]['localized_price'] = $v['localized_price'] + $price_bd;
//			$data['sku'][$k]['sku'] = time() .'_'. rand(10000, 99999). rand(10000, 99999);
		}
		
		$arr = array(
			'spu' => $data['spu'],
			'sku' => $data['sku'][0],
		);
		$product_add = $call_wish->product_add($arr);
		if ($product_add['code'] != 0) {
			//// 新增产品上传记录
			$sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `data_jkfh`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['parent_sku']}', 2, '{$product_add['message']}', '{$sku_list}', '{$data['time']}', now())";
			db::insert($sql);
			
			return $product_add['message'];
		}
		
		//// 上传剩余 SKU
		unset($data['sku'][0]);// 去除第一个
		if (!empty($data['sku'])) {
			foreach ($data['sku'] as $k => $v) {
				$v['parent_sku'] = $data['spu']['parent_sku'];// 父sku
				$product_sku_add = $call_wish->product_sku_add($v);
			}
		}
		
		//// 新增产品上传记录
		$sql = "insert into product_scjl(`shop_id`, `user_cj`, `spu`, `state`, `sku`, `create_time`, `time_sc`)
					values ({$data['store_id']}, {$data['user_info']['Id']}, '{$data['spu']['parent_sku']}', 3, '{$sku_list}', '{$data['time']}', now())";
		db::insert($sql);
		
		return 1;
	}
	

    //curl
    public function curls($url, $post = false, $head = '')
    {

        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if (!empty($head)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head); // 请求头部
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if (!empty($post)) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        //echo "<pre>";
        //var_dump(json_decode($res,true));die;

        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式
    }


    public function cate($data, $pid, $platform_id)
    {
        if ($platform_id == 3) {
            foreach ($data as $key => $value) {
                //if($pid!==0){
                //var_dump($value);die;
                //}
                $insert['category_id'] = $value['category_id'];

                $insert['name'] = $value['name'];
                $insert['pid'] = $pid;
                $insert['platform_id'] = $platform_id;
                $category = DB::table('category')->insertGetId($insert);
                if (isset($value['children'])) {
                    $this->cate($value['children'], $category, $platform_id);
                }
            }
        } elseif ($platform_id == 4) {
            //echo "11";die;
            foreach ($data as $key => $value) {
                //if($pid!==0){
                //var_dump($value);die;
                //}
                $insert['category_id'] = $value['category_id'];

                $insert['name'] = $value['category_name'];
                $insert['pid'] = $pid;
                $insert['platform_id'] = $platform_id;
                $category = DB::table('category')->insertGetId($insert);
                //var_dump($category);
                if (isset($value['child_category'])) {
                    $this->cate($value['child_category'], $category, $platform_id);
                }
            }
        }

        $return = 1;
        return $return;
    }

    public function find_child(&$arr, $id)
    {
        $childs = array();
        foreach ($arr as $k => $v) {
            if ($v['pid'] == $id) {
                $childs[] = $v;
            }
        }
        return $childs;

    }

    public function cate_arr($data, $pid)
    {
        $childs = $this->find_child($data, $pid);
        if (empty($childs)) {
            return null;
        }
        foreach ($childs as $k => $v) {
            $sql = "select * from category where platform_id={$v['platform_id']} and pid={$v['Id']}"; //and pid=0
            $category = json_decode(json_encode(db::select($sql)), true);
            if (!empty($category)) {
                $rescurTree = $this->cate_arr($data, $v['Id']);
                if (null != $rescurTree) {
                    $childs[$k]['childs'] = $rescurTree;
                }
            }


        }
        return $childs;
    }

    public function spu_rollback($data){
        $user_id = $data['user_info']['Id'];
        $time = date("Y-m-d H:i:s");
        $spu_id = $data['spu_id'];
        $sql = "select * from spu where Id = {$spu_id}";
        $spu = json_decode(json_encode(db::select($sql)), true);
        if(!empty($spu)){
            $sql = "update spu
				set handle_time='{$time}',state=2,user_cl={$user_id}
				where `Id` = {$spu_id}";
            //var_dump($sql);die;
            $res = db::update($sql);
            if($res!==false){
                return 1;
            }else{
                return "回退失败";
            }
        }else{
            return "spu不存在";
        }
    }



    //测试接口
    //
    public function lzd_croup($data)
    {
        $accessToken = "50000600406yuJabrM1b0b8b48EvDKHqwttgY4IwDJw9VQC7ieq5syWGfJdjtAP";
        //$urls = "../app/Libs/lazop/php/Autoloader.php";
        $url = "https://api.lazada.com.my/rest";
        $appkey = "115685";
        $appSecret = "WjfKuQH77FtwCS9gnn2sI75CS0sljiyc";
        $urls = "D:\phpstudy_pro\WWW\zity\zity\app\Libs\lazop\php\Autoloader.php";
        include_once($urls);
        $lazada = new \LazopClient($url, $appkey, $appSecret);
        $request = new \LazopRequest('/product/update');
        $request->addApiParam('payload', "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> <Request>     <Product>     <ItemId>2080572521</ItemId>         <Attributes>             <name>api update product sample</name>             <short_description>This is an amazing product</short_description>             <delivery_option_sof>No</delivery_option_sof>             <!--should be set as \u2018Yes\u2019 only for products to be delivered by seller-->         </Attributes>         <Skus>             <Sku>         <SkuId>234</SkuId>                 <SellerSku>api-create-test1-14</SellerSku>                 <quantity>88</quantity>                 <price>350</price>                 <package_length>12</package_length>                 <package_height>23</package_height>                 <package_weight>34</package_weight>                 <package_width>45</package_width>                 <Images></Images>             </Sku>                    </Skus>     </Product> </Request>");
        $resData = $lazada->execute($request, $accessToken);
        $resData = json_decode($resData, true);
        var_dump($resData);
        die;


    }

    //测试vova尺码表上传
    public function vova_size($data)
    {
        $size = [['Size', 'S', 'M', 'L'], ['Shoulder', '35', '36', '37']];
        $sizeJson = json_encode($size);
        var_dump($size);
        die;
        //($sizeJson);
        $param = [
            'token' => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1OTAzODcxMDgsInNjb3BlIjpbImdldCIsInBvc3QiXSwidWlkIjoiNDQwNDIiLCJ1TmFtZSI6IkVSUFx1OGQ1Ylx1NzZkMiJ9.qc8CCme2PQg6KXNxZlJUoOxmmiOqs2XxWBjelhP7aGQ',
            'product_id' => "71795309",
            'size_data' => $size,
            'size_remark' => 0
        ];
        //var_dump($param);die;
        $post = json_encode($param);
        //var_dump($post);die;
        $http = "https://merchant.vova.com.hk/api/v1/product/uploadSizeChart";
        $vova = $this->curls($http, $post);
        $vovaData = json_decode($vova, true);
        var_dump($vovaData);
        die;
    }

    public function getSpuBindSuppliers($params)
    {
        $spuBindSupplier = db::table('self_spu_info_attr')
            ->where('status', 1)
            ->whereNotNull('suppliers_id');

        if (isset($params['base_spu_id']))
        {
            $spuBindSupplier = $spuBindSupplier->where('base_spu_id', $params['base_spu_id']);
        }

        if (isset($params['spu_id']))
        {
            $spu = db::table('self_spu')->where('id', $params['spu_id'])->select(['base_spu_id'])->first();
            $spuBindSupplier = $spuBindSupplier->where('base_spu_id', $spu->base_spu_id);
        }
        $spuBindSupplier = $spuBindSupplier->get();

        $supplierMdl = db::table('suppliers')
            ->get()
            ->keyBy('Id');

        $list = [];
        foreach ($spuBindSupplier as $v){
            $v->supplier_id = $v->suppliers_id;
            $v->supplier_name = '';
            if (isset($supplierMdl[$v->suppliers_id])){
                $v->supplier_name = $supplierMdl[$v->suppliers_id]->name;
            }
            $list[] = [
                'id' => $v->supplier_id,
                'name' => $v->supplier_name
            ];
        }

        return['code' => 200, 'msg' => '获取成功！', 'data' => $list];
    }

    /**
     * @Desc:保存报价数据
     * @param $params
     * @author: Liu Sinian
     * @Time: 2023/9/10 17:51
     */
    public function saveSelfSpuQuotation($params)
    {
        try {
            $params = $this->_checkSaveSelfSpuQuotation($params);
            db::beginTransaction();
            if (isset($params['id'])){
                // 更新
                $id = $params['id'];
                $save = [
                    'spu_id' => $params['spu_id'],
                    'spu' => $params['spu'],
                    'maker_id' => $params['maker_id'],
                    'updated_at' => date('Y-m-d H:i:s'),
//                    'supplier_ids' => $params['supplier_ids']
                ];
                $update = db::table('self_spu_quotation_demand')
                    ->where('id', $id)
                    ->update($save);
                if (empty($update)){
                    throw new \Exception('修改失败，数据无变化！');
                }
            }else{
                // 新增
                $save = [
                    'spu_id' => $params['spu_id'],
                    'spu' => $params['spu'],
                    'status' => 0,
                    'user_id' => $params['user_id'],
                    'maker_id' => $params['maker_id'],
                    'created_at' => date('Y-m-d H:i:s'),
//                    'supplier_ids' => $params['supplier_ids']
                ];
                $id = db::table('self_spu_quotation_demand')
                    ->insertGetId($save);
                if (empty($id)){
                    throw new \Exception('报价需求新增失败！');
                }

                $update2 = db::table('self_spu')
                    ->where('id', $params['spu_id'])
                    ->update(['spu_status' => 1]);
                if (empty($update2)){
                    throw new \Exception('spu产品状态更新失败！');
                }
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存报价需求成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    protected function _checkSaveSelfSpuQuotation($params)
    {
        // 判断是否给定创建人
        if (!isset($params['user_id']) || empty($params['user_id'])) {
            if (isset($params['token']) && !empty($params['token'])) {
                $users = db::table('users')->where('token', $params['token'])->first();
                if ($users) {
                    $params['user_id'] = $users->Id;
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            } else {
                throw new \Exception('未给定创建人标识！');
            }
        }
        if (!isset($params['spu_id'])) {
            throw new \Exception('未给定spu标识！');
        } else {
            $spuMdl = db::table('self_spu')->where('id', $params['spu_id'])->first();
            if (empty($spuMdl)) {
                throw new \Exception('spu信息不存在！');
            }
            $params['spu'] = $spuMdl->old_spu ?? $spuMdl->spu;
        }
//        if (!isset($params['supplier_ids'])) {
//            throw new \Exception('未给定供应商标识！');
//        }
//
//        if (!is_array($params['supplier_ids'])) {
//            throw new \Exception('供应商标识给定格式不正确！');
//        }
//        $params['supplier_ids'] = implode(',', $params['supplier_ids']);

        if (!isset($params['maker_id'])) {
            throw new \Exception('未给定报价执行人！');
        } else {
            $users = db::table('users')->where('Id', $params['maker_id'])->first();
            if (empty($users)) {
                throw new \Exception('报价人信息不存在！');
            }
        }
        if (isset($params['id'])) {
            $quotationMdl = db::table('self_spu_quotation_demand')
                ->where('id', $params['id'])
                ->first();
            if (empty($quotationMdl)) {
                throw new \Exception('报价需求不存在！');
            }
            if (!in_array($quotationMdl->status, [0, 1])) {
                throw new \Exception('报价不处于待报价/报价中不可修改！');
            }
            $demandMdl = db::table('self_spu_quotation_demand')
                ->where('spu_id', $params['spu_id'])
                ->where('id', '<>', $params['id'])
                ->first();
            if (!empty($demandMdl)){
                throw new \Exception('已存在spu：'.$demandMdl->spu.'的报价需求，不可再次发布！');
            }
//            if ($spuMdl->spu_status != 1){
//                throw new \Exception('spu不处于待报价状态不可修改报价需求！');
//            }
        }else{
            if ($spuMdl->spu_status != 0){
                throw new \Exception('spu不处于开发中状态不可新增报价需求！');
            }
            $demandMdl = db::table('self_spu_quotation_demand')
                ->where('spu_id', $params['spu_id'])
                ->first();
            if (!empty($demandMdl)){
                throw new \Exception('已存在spu：'.$demandMdl->spu.'的报价需求，不可再次发布！');
            }
        }

        return $params;
    }

    public function spuQuotation($params)
    {
        try {
            $params = $this->_checkSpuQuotation($params);
            $error = '';
            db::beginTransaction();
            if (isset($params['id'])){
                foreach ($params['supplier_items'] as $supplier){
                    $update = db::table('self_spu_quotation_log')
                        ->where('id', $params['id'])
                        ->update([
                            'updated_at' => date('Y-m-d H:i:s'),
                            'supplier_id' => $supplier['supplier_id'],
                            'price' => $supplier['price'],
                            'memo' => $supplier['memo'] ?? ''
                        ]);
                }
            }else{
                $demandMdl = db::table('self_spu_quotation_demand')
                    ->where('id', $params['quotation_id'])
                    ->first();
                $logMdl = db::table('self_spu_quotation_log')
                    ->where('quotation_id', $demandMdl->id)
                    ->where('sort', '<', $demandMdl->num)
                    ->update(['is_update' => 0]);
                foreach ($params['supplier_items'] as $supplier){
                    $save = [
                        'quotation_id' => $demandMdl->id,
                        'spu_id' => $demandMdl->spu_id,
                        'spu' => $demandMdl->spu,
                        'supplier_id' => $supplier['supplier_id'],
                        'user_id' => $demandMdl->maker_id,
                        'created_at' => date('Y-m-d H:i:s'),
                        'sort' => $params['num'],
                        'price' => $supplier['price'],
                        'memo' => $supplier['memo'] ?? ''
                    ];
                    $logId = db::table('self_spu_quotation_log')
                        ->insertGetId($save);
                    if (empty($logId)){
                        $error .= 'spu：'.$demandMdl->spu.'，supplier_id：'.$supplier['supplier_id'].'报价日志保存失败！';
                    }
                }

//                $save = [
//                    'quotation_id' => $demandMdl->id,
//                    'spu_id' => $demandMdl->spu_id,
//                    'spu' => $demandMdl->spu,
//                    'user_id' => $demandMdl->maker_id,
//                    'created_at' => date('Y-m-d H:i:s'),
//                    'sort' => $params['num'],
//                ];
//                $logId = db::table('self_spu_quotation_log')
//                    ->insertGetId($save);
//                if (empty($logId)){
//                    $error .= 'spu：'.$demandMdl->spu.'报价日志保存失败！';
//                }
//                $save = [
//                    'num' => $params['num']
//                ];
                $save = [];
                if (isset($params['start_quotation_date'])) {
                    $save['start_quotation_date'] = $params['start_quotation_date'];
                    $update2 = db::table('self_spu')
                        ->where('id', $demandMdl->spu_id)
                        ->update(['spu_status' => 2]);
//                    if (empty($update2)){
//                        throw new \Exception('spu产品状态更新失败！');
//                    }
                }
                if (!empty($save)){
                    $update = db::table('self_spu_quotation_demand')
                        ->where('id', $params['quotation_id'])
                        ->update($save);
                }
//                if (empty($update)){
//                    throw new \Exception('报价需求状态更新失败！');
//                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    protected function _checkSpuQuotation($params)
    {
        // 判断是否给定创建人
        if (!isset($params['user_id']) || empty($params['user_id'])) {
            if (isset($params['token']) && !empty($params['token'])) {
                $users = db::table('users')->where('token', $params['token'])->first();
                if ($users) {
                    $params['user_id'] = $users->Id;
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            } else {
                throw new \Exception('未给定创建人标识！');
            }
        }
        if (isset($params['id'])){
            $logMdl = db::table('self_spu_quotation_log')
                ->where('id', $params['id'])
                ->first();
            if (empty($logMdl)){
                throw new \Exception('记录数据不存在！');
            }
            $allLogMdl = db::table('self_spu_quotation_log')
                ->where('quotation_id', $logMdl->quotation_id)
                ->where('sort', $logMdl->sort)
                ->where('id', '<>', $params['id'])
                ->get();
            $allLogList = [];
            foreach ($allLogMdl as $all){
                $allLogList[$all->supplier_id] = $all->price;
            }
            if ($logMdl->is_update != 1){
                throw new \Exception('该记录不可修改！');
            }
            if (!isset($params['supplier_items']) || !is_array($params['supplier_items']) || empty($params['supplier_items'])){
                throw new \Exception('未给定供应商明细或给定格式不正确！');
            }
            foreach ($params['supplier_items'] as $k => $v){
                if (!isset($v['supplier_id']) || empty($v['supplier_id'])){
                    throw new \Exception('未给定供应商标识！');
                }
                if (isset($allLogList[$v['supplier_id']])){
                    throw new \Exception('该轮报价中已有此供应商的报价记录，不可重复报价！');
                }
                $supplierMdl = db::table('suppliers')
                    ->where('Id', $v['supplier_id'])
                    ->first();
                if (empty($supplierMdl)){
                    throw new \Exception('第'.($k+1).'行供应商不存在！');
                }
                $supplierIds[] = $supplierMdl->Id;
                if (!isset($v['price']) || $v['price'] < 0){
                    throw new \Exception('报价价格未设置或不可小于0！');
                }
//                if (!isset($v['memo'])){
//                    throw new \Exception('未给定备注！');
//                }
            }
        }else{
            if (!isset($params['quotation_id'])){
                throw new \Exception('未给定报价需求id！');
            }
            $demandMdl = db::table('self_spu_quotation_demand')
                ->where('id', $params['quotation_id'])
                ->first();
            if (empty($demandMdl)){
                throw new \Exception('报价需求不存在！');
            }
            if (!in_array($demandMdl->status, [1])){
                throw new \Exception('报价需求状态非待报价/报价中，不可报价！');
            }
            if ($demandMdl->maker_id != $params['user_id']){
                throw new \Exception('非执行人不可发起报价！');
            }
            if ($demandMdl->num > 3){
                throw new \Exception('报价不可超过三次！');
            }
            $logMdl = db::table('self_spu_quotation_log')
                ->where('quotation_id', $params['quotation_id'])
                ->get();
            $check = [];
            $num = $demandMdl->num;
            foreach ($logMdl as $log)
            {
//                if ($log->sort == $num){
//                    throw new \Exception('第'.$demandMdl->num.'次存报价已执行，不可再次新增！');
//                }
                if (!isset($check[$log->sort])){
                    $check[$log->sort] = 0;
                }
                if ($log->price > 0){
                    $check[$log->sort] = 1;
                }
            }
            foreach ($check as $k => $c){
                if ($c == 0){
                    throw new \Exception('第'.$k.'次存报价未被执行不可确认！');
                }
            }
            if (!isset($params['supplier_items']) || !is_array($params['supplier_items']) || empty($params['supplier_items'])){
                throw new \Exception('未给定供应商明细或给定格式不正确！');
            }
            $supplierIds = [];
            $logMdl2 = db::table('self_spu_quotation_log')
                ->where('quotation_id', $params['quotation_id'])
                ->where('sort', $demandMdl->num)
                ->get();
            foreach ($logMdl2 as $log2){
                $supplierIds[] = $log2->supplier_id;
            }
            foreach ($params['supplier_items'] as $k => $v){
                if (!isset($v['supplier_id']) || empty($v['supplier_id'])){
                    throw new \Exception('未给定供应商标识！');
                }
                if (in_array($v['supplier_id'], $supplierIds)){
                    throw new \Exception('第'.($k+1).'行供应商在本轮报价中已报价，不可重复报价！');
                }
                $supplierMdl = db::table('suppliers')
                    ->where('Id', $v['supplier_id'])
                    ->first();
                if (empty($supplierMdl)){
                    throw new \Exception('第'.($k+1).'行供应商不存在！');
                }
                $supplierIds[] = $supplierMdl->Id;
                if (!isset($v['price']) || $v['price'] < 0){
                    throw new \Exception('报价价格未设置或不可小于0！');
                }
//                if (!isset($v['memo'])){
//                    throw new \Exception('未给定备注！');
//                }
            }
            $spuMdl = db::table('self_spu')
                ->where('id', $demandMdl->spu_id)
                ->first();
            if (empty($spuMdl)){
                throw new \Exception('SPU数据不存在！');
            }
            if ($num == 1){
                $params['start_quotation_date'] = date('Y-m-d H:i:s');
            }
            $params['num'] = $num;
        }

        return $params;
    }

    public function getSpuQuotationLogList($params)
    {
        $quotationLogMdl = db::table('self_spu_quotation_log');

        if (isset($params['quotation'])){
            $quotationLogMdl = $quotationLogMdl->where('quotation_id', $params['quotation']);
        }

        $count = $quotationLogMdl->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $quotationLogMdl = $quotationLogMdl->limit($limit)->offset($offsetNum);
        }

        $supplierMdl = db::table('suppliers')
            ->get()
            ->keyBy('Id');
        $quotationLogMdl = $quotationLogMdl->orderBy('created_at', 'ASC')
            ->get();
        $userMdl = db::table('users')->get()->keyBy('Id');
        foreach ($quotationLogMdl as $item)
        {
            $item->supplier_name = $supplierMdl[$item->supplier_id]->supplier_no ?? '';
            if (isset($params['is_save']) && $params['is_save'] == 1){
                $item->fid = $item->id;
                unset($item->id);
            }
            $item->user_name = $userMdl[$item->user_id]->account ?? '';
            $item->sort = '第'.$item->sort.'轮';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $quotationLogMdl]];
    }

    public function getSpuQuotationList($params)
    {
        $quotationMdl = db::table('self_spu_quotation_demand');

        if (isset($params['status'])){
            $quotationMdl = $quotationMdl->where('status', $params['status']);
        }
        if (isset($params['spu_id'])){
            $quotationMdl = $quotationMdl->where('spu_id', $params['spu_id']);
        }
        if (isset($params['user_id'])){
            $quotationMdl = $quotationMdl->where('user_id', $params['user_id']);
        }
        if (isset($params['maker_id'])){
            $quotationMdl = $quotationMdl->where('maker_id', $params['maker_id']);
        }
        if (isset($params['id'])){
            $quotationMdl = $quotationMdl->where('id', $params['id']);
        }
        $count = $quotationMdl->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $quotationMdl = $quotationMdl->limit($limit)->offset($offsetNum);
        }
        $quotationMdl = $quotationMdl->orderBy('created_at', 'desc')
            ->get();
        $userMdl = db::table('users')
            ->get()
            ->keyBy('Id');
        $logMdl = db::table('self_spu_quotation_log')
            ->get();
        $logList = [];
        $supplierMdl = db::table('suppliers')
            ->get()
            ->pluck('supplier_no', 'Id');
        foreach ($logMdl as $l){
            $l->supplier_name = $supplierMdl[$l->supplier_id] ?? '';
            $l->sort_name = '第'.$l->sort.'轮';
            $logList[$l->quotation_id][] = $l;
        }
        $baseModel = new BaseModel();
        foreach ($quotationMdl as $v)
        {
            $v->img = $baseModel->GetSpuImg($v->spu);
            $self_spu_info = DB::table('self_spu_info as a')->leftjoin('self_spu as b','a.base_spu_id','=','b.base_spu_id')->where('b.id',$v->spu_id)
            ->select('sample_sheet')->first();
            if(!empty($self_spu_info)){
                $v->sample_sheet = $self_spu_info->sample_sheet;
            }else{
                $v->sample_sheet = '';
            }
            $v->user_name = $userMdl[$v->user_id]->account ?? '';
            $v->maker_name = $userMdl[$v->maker_id]->account ?? '';
            $v->status_name = Constant::QUOTATION_STATUS[$v->status] ?? '';
            $v->num = $v->num.'轮';
            $v->log_detail = $logList[$v->id] ?? [];
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $quotationMdl]];
    }

    public function deleteSpuQuotationDemand($params)
    {
        try {
            if (!isset($params['id']) || !is_array($params['id'])){
                throw new \Exception('未给定标识或给定的标识格式不正确！');
            }
            // 判断是否给定创建人
            if (!isset($params['user_id']) || empty($params['user_id'])) {
                if (isset($params['token']) && !empty($params['token'])) {
                    $users = db::table('users')->where('token', $params['token'])->first();
                    if ($users) {
                        $params['user_id'] = $users->Id;
                    } else {
                        throw new \Exception('未给定创建人标识！');
                    }
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $quotationMdl = db::table('self_spu_quotation_demand')->whereIn('id', $params['id'])->get()->keyBy('id');
            $error = '';
            $userMdl = db::table('users')->get()->keyBy('Id');
            db::beginTransaction();
            foreach ($params['id'] as $id){
                $quotation = $quotationMdl[$id] ?? [];
                if (isset($quotation)){
//                    if ($quotation->status != 0){
//                        $error .= '标识：'.$id.'状态非待报价，不可删除！';
//                    }
                    $spuMdl = db::table('self_spu')
                        ->where('id', $quotation->spu_id)
                        ->first();
                    if (!in_array($spuMdl->spu_status, [1, 2, 3])){
                        $error .= '标识：'.$id.',spu状态非待报价/报价中/报价完成，不可删除！';
                        continue;
                    }
                    if ($quotation->user_id != $params['user_id']){
                        $username = $userMdl[$quotation->user_id]->account ?? '';
                        $error .= '标识：'.$id.'该报价需求创建人为'.$username.'，非本人不可删除！';
                        continue;
                    }
                    $delete = db::table('self_spu_quotation_demand')
                        ->where('id', $params['id'])
                        ->delete();
                    $delete2 = db::table('self_spu_quotation_log')
                        ->where('quotation_id', $id)
                        ->delete();
                    $update2 = db::table('self_spu')
                        ->where('id', $quotation->spu_id)
                        ->update(['spu_status' => 0]);
                    if (empty($update2)){
                        $error .= '标识：'.$id.'产品状态更新失败，数据无变化！';
                        continue;
                    }
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '删除成功！删除：'.$delete.'条记录！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '删除失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function confirmQuotationCompletion($params)
    {
        try {
            if (!isset($params['id']) || !is_array($params['id'])){
                throw new \Exception('未给定标识或给定的标识格式不正确！');
            }
            // 判断是否给定创建人
            if (!isset($params['user_id']) || empty($params['user_id'])) {
                if (isset($params['token']) && !empty($params['token'])) {
                    $users = db::table('users')->where('token', $params['token'])->first();
                    if ($users) {
                        $params['user_id'] = $users->Id;
                    } else {
                        throw new \Exception('未给定创建人标识！');
                    }
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $quotationMdl = db::table('self_spu_quotation_demand')->whereIn('id', $params['id'])->get()->keyBy('id');
            $error = '';
            $userMdl = db::table('users')->get()->keyBy('Id');
            $logList = [];
            $logMdl = db::table('self_spu_quotation_log')
                ->whereIn('quotation_id', $params['id'])
                ->get();
            foreach ($logMdl as $l){
                $logList[$l->quotation_id][] = $l;
            }
            db::beginTransaction();
            foreach ($params['id'] as $id){
                $quotation = $quotationMdl[$id] ?? [];
                if (empty($quotation)){
                    $error .= '标识：'.$id.'确认失败，无数据！';
                    continue;
                }
                if ($quotation->status != 1){
                    $error .= '标识：'.$id.'状态非报价中，不可确认报价完成！';
                    continue;
                }
                if ($quotation->user_id != $params['user_id']){
                    $username = $userMdl[$quotation->user_id]->account ?? '';
                    $error .= '标识：'.$id.'该报价需求创建人为'.$username.'，不可确认报价完成！';
                    continue;
                }
                if (empty($logList[$id])){
                    $error .= '标识：'.$id.'记录为空，不可确认报价完成！';
                    continue;
                }
//                $check = [];
//                foreach ($logList[$id] as $log)
//                {
//                    if (!isset($check[$log->sort])){
//                        $check[$log->sort] = 0;
//                    }
//                    if ($log->price > 0){
//                        $check[$log->sort] = 1;
//                    }
//                }
//                foreach ($check as $k => $c){
//                    if ($c == 0){
//                        $error .='第'.$k.'次存在报价未被执行不可确认！';
//                        continue;
//                    }
//                }
                if ($quotation->num != 0){
                    $logMdl = db::table('self_spu_quotation_log')
                        ->where('quotation_id', $quotation->id)
                        ->where('price', '>', 0)
                        ->where('sort', $quotation->num)
                        ->get();
                    if ($logMdl->isEmpty()){
                        throw new \Exception('第'.$quotation->num.'轮报价未被执行！');
                    }
                }
                $update = db::table('self_spu_quotation_demand')
                    ->where('id', $params['id'])
                    ->update([
                        'status' => 2,
                        'end_quotation_date' => date('Y-m-d H:i:s')
                    ]);
                if (empty($update)){
                    $error .= '标识：'.$id.'报价需求状态更新失败，数据无变化！';
                    continue;
                }
                $update2 = db::table('self_spu')
                    ->where('id', $quotation->spu_id)
                    ->update(['spu_status' => 3]);
                if (empty($update2)){
                    $error .= '标识：'.$id.'产品状态更新失败，数据无变化！';
                    continue;
                }
                $update3 = db::table('self_spu_quotation_log')
                    ->where('quotation_id', $id)
                    ->update(['is_update' => 0]);
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '确认报价成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '确认报价失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getProofingDemandList($params)
    {
        $proofingMdl = db::table('self_spu_proofing_demand');

        if (isset($params['status'])){
            $proofingMdl = $proofingMdl->where('status', $params['status']);
        }
        if (isset($params['spu_id'])){
            $proofingMdl = $proofingMdl->where('spu_id', $params['spu_id']);
        }
        if (isset($params['user_id'])){
            $proofingMdl = $proofingMdl->where('user_id', $params['user_id']);
        }
        if (isset($params['maker_id'])){
            $proofingMdl = $proofingMdl->where('maker_id', $params['maker_id']);
        }
        if (isset($params['id'])){
            $proofingMdl = $proofingMdl->where('id', $params['id']);
        }
        $count = $proofingMdl->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $proofingMdl = $proofingMdl->limit($limit)->offset($offsetNum);
        }
        $proofingMdl = $proofingMdl->orderBy('created_at', 'desc')
            ->get();
        $userMdl = db::table('users')
            ->get()
            ->keyBy('Id');
        $logMdl = db::table('self_spu_proofing_log')
            ->get();
        $logList = [];
        $supplierMdl = db::table('suppliers')
            ->get()
            ->pluck('supplier_no', 'Id');
        foreach ($logMdl as $l){
            $l->supplier_name = $supplierMdl[$l->supplier_id] ?? '';
            $l->img = json_decode($l->img, true);
            $l->sort_name = '第'.$l->sort.'轮';
            $logList[$l->proofing_id][] = $l;
        }
        $baseModel = new BaseModel();
        foreach ($proofingMdl as $v)
        {
            $v->img = $baseModel->GetSpuImg($v->spu);
            $self_spu_info = DB::table('self_spu_info as a')->leftjoin('self_spu as b','a.base_spu_id','=','b.base_spu_id')->where('b.id',$v->spu_id)
                ->select('sample_sheet')->first();
            if(!empty($self_spu_info)){
                $v->sample_sheet = $self_spu_info->sample_sheet;
            }else{
                $v->sample_sheet = '';
            }
            $v->user_name = $userMdl[$v->user_id]->account ?? '';
            $v->maker_name = $userMdl[$v->maker_id]->account ?? '';
            $v->status_name = Constant::PROOFING_STATUS[$v->status] ?? '';
            $v->num = $v->num.'轮';
            $v->log_detail = $logList[$v->id] ?? [];
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $proofingMdl]];
    }

    public function saveProofingDemand($params)
    {
        try {
            $params = $this->_checkSaveSelfSpuProofingDemand($params);
            db::beginTransaction();
            if (isset($params['id'])){
                // 更新
                $id = $params['id'];
                $save = [
                    'spu_id' => $params['spu_id'],
                    'spu' => $params['spu'],
                    'maker_id' => $params['maker_id'],
                    'updated_at' => date('Y-m-d H:i:s'),
//                    'supplier_ids' => $params['supplier_ids']
                ];
                $update = db::table('self_spu_proofing_demand')
                    ->where('id', $id)
                    ->update($save);
                if (empty($update)){
                    throw new \Exception('修改失败，数据无变化！');
                }
            }else{
                // 新增
                $save = [
                    'spu_id' => $params['spu_id'],
                    'spu' => $params['spu'],
                    'status' => 0,
                    'user_id' => $params['user_id'],
                    'maker_id' => $params['maker_id'],
                    'created_at' => date('Y-m-d H:i:s'),
//                    'supplier_ids' => $params['supplier_ids']
                ];
                $id = db::table('self_spu_proofing_demand')
                    ->insertGetId($save);
                if (empty($id)){
                    throw new \Exception('打样需求新增失败！');
                }

                $update2 = db::table('self_spu')
                    ->where('id', $params['spu_id'])
                    ->update(['spu_status' => 4]);
                if (empty($update2)){
                    throw new \Exception('spu产品状态更新失败！');
                }
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存打样需求成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    protected function _checkSaveSelfSpuProofingDemand($params)
    {
        // 判断是否给定创建人
        if (!isset($params['user_id']) || empty($params['user_id'])) {
            if (isset($params['token']) && !empty($params['token'])) {
                $users = db::table('users')->where('token', $params['token'])->first();
                if ($users) {
                    $params['user_id'] = $users->Id;
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            } else {
                throw new \Exception('未给定创建人标识！');
            }
        }
        if (!isset($params['spu_id'])) {
            throw new \Exception('未给定spu标识！');
        } else {
            $spuMdl = db::table('self_spu')->where('id', $params['spu_id'])->first();
            if (empty($spuMdl)) {
                throw new \Exception('spu信息不存在！');
            }
            $params['spu'] = $spuMdl->old_spu ?? $spuMdl->spu;
        }
//        if (!isset($params['supplier_ids'])) {
//            throw new \Exception('未给定供应商标识！');
//        }
//
//        if (!is_array($params['supplier_ids'])) {
//            throw new \Exception('供应商标识给定格式不正确！');
//        }
//        $params['supplier_ids'] = implode(',', $params['supplier_ids']);

        if (!isset($params['maker_id'])) {
            throw new \Exception('未给定打样执行人！');
        } else {
            $users = db::table('users')->where('Id', $params['maker_id'])->first();
            if (empty($users)) {
                throw new \Exception('打样人信息不存在！');
            }
        }
        if (isset($params['id'])) {
            $proofingMdl = db::table('self_spu_proofing_demand')
                ->where('id', $params['id'])
                ->first();
            if (empty($proofingMdl)) {
                throw new \Exception('打样需求不存在！');
            }
            if (!in_array($proofingMdl->status, [0, 1])) {
                throw new \Exception('打样需求非待打样/打样中状态不可修改！');
            }
            if ($proofingMdl->user_id != $params['user_id']){
                throw new \Exception('非本人创建不可修改！');
            }
            $demandMdl = db::table('self_spu_proofing_demand')
                ->where('spu_id', $params['spu_id'])
                ->where('id', '<>', $params['id'])
                ->first();
            if (!empty($demandMdl)){
                throw new \Exception('已存在spu：'.$demandMdl->spu.'的打样需求，不可再次发布！');
            }
//            if ($spuMdl->spu_status != 4){
//                throw new \Exception('spu不处于待打样状态不可修改打样需求！');
//            }
        }else{
            if ($spuMdl->spu_status != 3){
                throw new \Exception('spu不处于报价完成状态不可新增打样需求！');
            }
            $demandMdl = db::table('self_spu_proofing_demand')
                ->where('spu_id', $params['spu_id'])
                ->first();
//            if ($params['token'] == '4E55F683DB24324A15B08F193312D3CD'){
//                var_dump($demandMdl);
//                var_dump($params['spu_id']);
//                exit();
//            }
            if (!empty($demandMdl)){
                throw new \Exception('已存在spu：'.$demandMdl->spu.'的打样需求，不可再次发布！');
            }
        }
//        if ($params['token'] == '4E55F683DB24324A15B08F193312D3CD'){
//            var_dump(isset($params['id']));
//            exit();
//        }

        return $params;
    }

    public function spuProofing($params)
    {
        try {
            $params = $this->_checkSpuProofing($params);
            $error = '';
            db::beginTransaction();
            if (isset($params['id'])){
                foreach ($params['supplier_items'] as $supplier){
                    $update = db::table('self_spu_proofing_log')
                        ->where('id', $params['id'])
                        ->update([
                            'updated_at' => date('Y-m-d H:i:s'),
                            'supplier_id' => $supplier['supplier_id'],
                            'img' => json_encode($supplier['img']),
                            'memo' => $supplier['memo'] ?? ''
                        ]);
                }
            }else{
                $demandMdl = db::table('self_spu_proofing_demand')
                    ->where('id', $params['proofing_id'])
                    ->first();
                $logMdl = db::table('self_spu_proofing_log')
                    ->where('sort', '<', $demandMdl->num)
                    ->where('proofing_id', $demandMdl->id)
                    ->update(['is_update' => 0]);
                foreach ($params['supplier_items'] as $supplier){
                    $save = [
                        'proofing_id' => $demandMdl->id,
                        'spu_id' => $demandMdl->spu_id,
                        'spu' => $demandMdl->spu,
                        'supplier_id' => $supplier['supplier_id'],
                        'user_id' => $demandMdl->maker_id,
                        'created_at' => date('Y-m-d H:i:s'),
                        'sort' => $params['num'],
                        'img' => json_encode($supplier['img']),
                        'memo' => $supplier['memo'] ?? ''
                    ];
                    $logId = db::table('self_spu_proofing_log')
                        ->insertGetId($save);
                    if (empty($logId)){
                        $error .= 'spu：'.$demandMdl->spu.'，supplier_id：'.$supplier['supplier_id'].'报价日志保存失败！';
                    }
                }

//                $save = [
//                    'proofing_id' => $demandMdl->id,
//                    'spu_id' => $demandMdl->spu_id,
//                    'spu' => $demandMdl->spu,
//                    'user_id' => $demandMdl->maker_id,
//                    'created_at' => date('Y-m-d H:i:s'),
//                    'sort' => $params['num'],
//                ];
//                $logId = db::table('self_spu_proofing_log')
//                    ->insertGetId($save);
//                if (empty($logId)){
//                    $error .= 'spu：'.$demandMdl->spu.'打样日志保存失败！';
//                }
//                $save = [
//                    'num' => $params['num']
//                ];
                $save = [];
                if (isset($params['start_proofing_date'])) {
                    $save['start_proofing_date'] = $params['start_proofing_date'];
//                    $save['status'] = 1;
                    $update2 = db::table('self_spu')
                        ->where('id', $demandMdl->spu_id)
                        ->update(['spu_status' => 5]);
//                    if (empty($update2)){
//                        throw new \Exception('spu产品状态更新失败！');
//                    }
                }
                if (!empty($save)){
                    $update = db::table('self_spu_proofing_demand')
                        ->where('id', $params['proofing_id'])
                        ->update($save);
                }
//                if (empty($update)){
//                    throw new \Exception('打样需求状态更新失败！');
//                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    protected function _checkSpuProofing($params)
    {
        // 判断是否给定创建人
        if (!isset($params['user_id']) || empty($params['user_id'])) {
            if (isset($params['token']) && !empty($params['token'])) {
                $users = db::table('users')->where('token', $params['token'])->first();
                if ($users) {
                    $params['user_id'] = $users->Id;
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            } else {
                throw new \Exception('未给定创建人标识！');
            }
        }
        if (isset($params['id'])){
            $logMdl = db::table('self_spu_proofing_log')
                ->where('id', $params['id'])
                ->first();
            if (empty($logMdl)){
                throw new \Exception('记录数据不存在！');
            }
            $allLogMdl = db::table('self_spu_proofing_log')
                ->where('proofing_id', $logMdl->proofing_id)
                ->where('sort', $logMdl->sort)
                ->where('id', '<>', $params['id'])
                ->get();
            $allLogList = [];
            foreach ($allLogMdl as $all){
                $allLogList[$all->supplier_id] = $all->img;
            }
            if ($logMdl->is_update != 1){
                throw new \Exception('该记录不可修改！');
            }
            if (!isset($params['supplier_items']) || !is_array($params['supplier_items']) || empty($params['supplier_items'])){
                throw new \Exception('未给定供应商明细或给定格式不正确！');
            }
            foreach ($params['supplier_items'] as $k => $v){
                if (!isset($v['supplier_id']) || empty($v['supplier_id'])){
                    throw new \Exception('未给定供应商标识！');
                }
                if (isset($allLogList[$v['supplier_id']])){
                    throw new \Exception('该轮报价中已有此供应商的打样记录，不可重复打样！');
                }
                $supplierMdl = db::table('suppliers')
                    ->where('Id', $v['supplier_id'])
                    ->first();
                if (empty($supplierMdl)){
                    throw new \Exception('第'.($k+1).'行供应商不存在！');
                }
                if (!isset($v['img']) || !is_array($v['img'])){
                    throw new \Exception('打样图片未给定或格式不正确！');
                }
//                if (!isset($v['memo'])){
//                    throw new \Exception('未给定备注！');
//                }
            }
        }else{
            if (!isset($params['proofing_id'])){
                throw new \Exception('未给定打样需求标识！');
            }
            $demandMdl = db::table('self_spu_proofing_demand')
                ->where('id', $params['proofing_id'])
                ->first();
            if (empty($demandMdl)){
                throw new \Exception('打样需求不存在！');
            }
            if (!in_array($demandMdl->status, [1])){
                throw new \Exception('打样需求状态非待打样/打样中，不可打样！');
            }
            if ($demandMdl->maker_id != $params['user_id']){
                throw new \Exception('非执行人不可发起打样！');
            }
            $num = $demandMdl->num;
            $logMdl = db::table('self_spu_proofing_log')
                ->where('proofing_id', $params['proofing_id'])
                ->get();
            $check = [];
            foreach ($logMdl as $log)
            {
                if (!isset($check[$log->sort])){
                    $check[$log->sort] = 0;
                }
                $img = json_decode($log->img, true);
                if (!empty($img)){
                    $check[$log->sort] = 1;
                }
            }
            foreach ($check as $k => $c){
                if ($c == 0){
                    throw new \Exception('第'.$k.'次存打样未被执行不可确认！');
                }
            }
            if (!isset($params['supplier_items']) || !is_array($params['supplier_items']) || empty($params['supplier_items'])){
                throw new \Exception('未给定供应商明细或给定格式不正确！');
            }
            $supplierIds = [];
            $logMdl2 = db::table('self_spu_proofing_log')
                ->where('proofing_id', $params['proofing_id'])
                ->where('sort', $demandMdl->num)
                ->get();
            foreach ($logMdl2 as $log2){
                $supplierIds[] = $log2->supplier_id;
            }
            foreach ($params['supplier_items'] as $k => $v){
                if (!isset($v['supplier_id']) || empty($v['supplier_id'])){
                    throw new \Exception('未给定供应商标识！');
                }
                if (in_array($v['supplier_id'], $supplierIds)){
                    throw new \Exception('第'.($k+1).'行供应商在本轮报价中已打样，不可重复打样！');
                }
                $supplierMdl = db::table('suppliers')
                    ->where('Id', $v['supplier_id'])
                    ->first();
                if (empty($supplierMdl)){
                    throw new \Exception('第'.($k+1).'行供应商不存在！');
                }
                $supplierIds[] = $supplierMdl->Id;
                if (!isset($v['img']) || !is_array($v['img'])){
                    throw new \Exception('打样图片未给定或格式不正确！');
                }
//                if (!isset($v['memo'])){
//                    throw new \Exception('未给定备注！');
//                }
            }
            $spuMdl = db::table('self_spu')
                ->where('id', $demandMdl->spu_id)
                ->first();
            if (empty($spuMdl)){
                throw new \Exception('SPU数据不存在！');
            }
//            $spuInfoMdl = db::table('self_spu_info_attr')
//                ->where('base_spu_id', $spuMdl->base_spu_id)
//                ->where('status', 1)
//                ->get();
//            if ($spuInfoMdl->isEmpty()){
//                throw new \Exception('该spu绑定数据为空！');
//            }
//            $supplierIds = [];
//            foreach ($spuInfoMdl as $s){
//                if (!empty($s->suppliers_id)){
//                    $supplierIds[] = $s->suppliers_id;
//                }
//            }
//            if (empty($supplierIds)){
//                throw new \Exception('该spu未绑定工厂');
//            }
//            $params['supplier_ids'] = array_unique($supplierIds);
            if ($num > 3){
                throw new \Exception('打样不可超过三次！');
            }
            $params['num'] = $num;
            if ($num == 1){
                $params['start_proofing_date'] = date('Y-m-d H:i:s');
            }
        }

        return $params;
    }

    public function getSpuProofingLogList($params)
    {
        $proofingLogMdl = db::table('self_spu_proofing_log');

        if (isset($params['proofing_id'])){
            $proofingLogMdl = $proofingLogMdl->where('proofing_id', $params['proofing_id']);
        }

        if (isset($params['is_save']) && $params['is_save'] == 1)
        {
            $proofingLogMdl = $proofingLogMdl->where('fid', 0);
        }else if (isset($params['is_save']) && $params['is_save'] == 2)
        {
            $proofingLogMdl = $proofingLogMdl->where('fid', '<>', 0);
        }
        $count = $proofingLogMdl->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $proofingLogMdl = $proofingLogMdl->limit($limit)->offset($offsetNum);
        }

        $supplierMdl = db::table('suppliers')
            ->get()
            ->keyBy('Id');
        $proofingLogMdl = $proofingLogMdl->orderBy('created_at', 'ASC')
            ->get();
        $userMdl = db::table('users')->get()->keyBy('Id');
        foreach ($proofingLogMdl as $item)
        {
            $item->supplier_name = $supplierMdl[$item->supplier_id]->supplier_no ?? '';
            if (isset($params['is_save']) && $params['is_save'] == 1){
                $item->fid = $item->id;
                unset($item->id);
            }
            $item->user_name = $userMdl[$item->user_id]->account ?? '';
            $item->img = json_decode($item->img);
            $item->sort = '第'.$item->sort.'轮';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $proofingLogMdl]];
    }

    public function deleteSpuProofingDemand($params)
    {
        try {
            if (!isset($params['id']) || !is_array($params['id'])){
                throw new \Exception('未给定标识或给定的标识格式不正确！');
            }
            // 判断是否给定创建人
            if ((!isset($params['user_id']) || empty($params['user_id'])) ||
                !(isset($params['token']) && !empty($params['token']))
            ) {
                throw new \Exception('未给定创建人标识！');
            }

            $users = db::table('users')->where('token', $params['token'])->first();
            if (!$users) {
                throw new \Exception('未给定创建人标识！');
            }
            $params['user_id'] = $users->Id;

            $proofingMdl = db::table('self_spu_proofing_demand')->whereIn('id', $params['id'])->get()->keyBy('id');
            $error = '';
            $userMdl = db::table('users')->get()->keyBy('Id');
            db::beginTransaction();
            foreach ($params['id'] as $id){
                $proofing = $proofingMdl[$id] ?? [];
                if (isset($proofing)){
//                    if ($proofing->status != 0){
//                        $error .= '标识：'.$id.'状态非待打样，不可删除！';
//                    }
                    $spuMdl = db::table('self_spu')
                        ->where('id', $proofing->spu_id)
                        ->first();
                    if (!in_array($spuMdl->spu_status, [4, 5, 6])){
                        $error .= '标识：'.$id.',spu状态非待打样/打样中/打样完成，不可删除！';
                        continue;
                    }
                    if ($proofing->user_id != $params['user_id']){
                        $username = $userMdl[$proofing->user_id]->account ?? '';
                        $error .= '标识：'.$id.'该打样需求创建人为'.$username.'，非本人不可删除！';
                        continue;
                    }
                    $delete = db::table('self_spu_proofing_demand')
                        ->where('id', $params['id'])
                        ->delete();
                    $delete2 = db::table('self_spu_proofing_log')
                        ->where('proofing_id', $id)
                        ->delete();
                    $update2 = db::table('self_spu')
                        ->where('id', $proofing->spu_id)
                        ->update(['spu_status' => 3]);
                    if (empty($update2)){
                        $error .= '标识：'.$id.'产品状态更新失败，数据无变化！';
                        continue;
                    }
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '删除成功！删除：'.$delete.'条记录！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '删除失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function confirmProofingCompletion($params)
    {
        try {
            if (!isset($params['id']) || !is_array($params['id'])){
                throw new \Exception('未给定标识或给定的标识格式不正确！');
            }
            // 判断是否给定创建人
            if (!isset($params['user_id']) || empty($params['user_id'])) {
                if (isset($params['token']) && !empty($params['token'])) {
                    $users = db::table('users')->where('token', $params['token'])->first();
                    if ($users) {
                        $params['user_id'] = $users->Id;
                    } else {
                        throw new \Exception('未给定创建人标识！');
                    }
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $proofingMdl = db::table('self_spu_proofing_demand')->whereIn('id', $params['id'])->get()->keyBy('id');
            $error = '';
            $userMdl = db::table('users')->get()->keyBy('Id');
            $logList = [];
            $logMdl = db::table('self_spu_proofing_log')
                ->whereIn('proofing_id', $params['id'])
                ->get();
            foreach ($logMdl as $l){
                $logList[$l->proofing_id][] = $l;
            }
            db::beginTransaction();
            foreach ($params['id'] as $id){
                $proofing = $proofingMdl[$id] ?? [];
                if (empty($proofing)){
                    $error .= '标识：'.$id.'确认失败，无数据！';
                    continue;
                }
                if ($proofing->status != 1){
                    $error .= '标识：'.$id.'状态非打样中，不可确认报价完成！';
                    continue;
                }
                if ($proofing->user_id != $params['user_id']){
                    $username = $userMdl[$proofing->user_id]->account ?? '';
                    $error .= '标识：'.$id.'该打样需求创建人为'.$username.'，不可确认打样完成！';
                    continue;
                }
//                $check = [];
//                foreach ($logList[$id] as $log)
//                {
//                    if (!isset($check[$log->sort])){
//                        $check[$log->sort] = 0;
//                    }
//                    $img = json_decode($log->img, true);
//                    if (!empty($img)){
//                        $check[$log->sort] = 1;
//                    }
//                }
//                foreach ($check as $k => $c){
//                    if ($c == 0){
//                        $error .='第'.$k.'次存在打样未被执行不可确认！';
//                        continue;
//                    }
//                }
                if ($proofing->num != 0){
                    $logMdl = db::table('self_spu_quotation_log')
                        ->where('quotation_id', $proofing->id)
                        ->where('price', '>', 0)
                        ->where('sort', $proofing->num)
                        ->get();
                    if ($logMdl->isEmpty()){
                        $error .= '第'.$proofing->num.'轮报价未被执行！';
                        continue;
                    }
                }
                $update = db::table('self_spu_proofing_demand')
                    ->where('id', $params['id'])
                    ->update([
                        'status' => 2,
                        'end_proofing_date' => date('Y-m-d H:i:s')
                    ]);
                if (empty($update)){
                    $error .= '标识：'.$id.'打样需求状态更新失败，数据无变化！';
                    continue;
                }
                $update2 = db::table('self_spu')
                    ->where('id', $proofing->spu_id)
                    ->update(['spu_status' => 6]);
                if (empty($update2)){
                    $error .= '标识：'.$id.'产品状态更新失败，数据无变化！';
                    continue;
                }
                $update3 = db::table('self_spu_proofing_log')
                    ->where('proofing_id', $id)
                    ->update(['is_update' => 0]);
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::commit();
            return ['code' => 200, 'msg' => '确认打样成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '确认打样失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function publishQuotationTask($params)
    {
        try{
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给需求标识！');
            }
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $demandMdl = db::table('self_spu_quotation_demand')
                ->where('id', $params['id'])
                ->first();
            if (empty($demandMdl)){
                throw new \Exception('报价需求不存在！');
            }
            if (!in_array($demandMdl->status, [0, 1])){
                throw new \Exception('报价需求状态非待报价/报价中，不可报价！');
            }
            if ($demandMdl->user_id != $params['user_id']){
                throw new \Exception('非需求创建人不可发起报价！');
            }
            $num = $demandMdl->num + 1;
            if ($num > 3){
                throw new \Exception('报价不可超过三次！');
            }
            if ($demandMdl->num != 0){
                $logMdl = db::table('self_spu_quotation_log')
                    ->where('quotation_id', $demandMdl->id)
                    ->where('price', '>', 0)
                    ->where('sort', $demandMdl->num)
                    ->get();
                if ($logMdl->isEmpty()){
                    throw new \Exception('第'.$demandMdl->num.'轮报价未被执行！');
                }
            }
            $spuMdl = db::table('self_spu')
                ->where('id', $demandMdl->spu_id)
                ->first();
            if (empty($spuMdl)){
                throw new \Exception('SPU数据不存在！');
            }
//            $spuInfoMdl = db::table('self_spu_info_attr')
//                ->where('base_spu_id', $spuMdl->base_spu_id)
//                ->where('status', 1)
//                ->get();
//            if ($spuInfoMdl->isEmpty()){
//                throw new \Exception('该spu绑定数据为空！');
//            }
//            $supplierIds = [];
//            foreach ($spuInfoMdl as $s){
//                if (!empty($s->suppliers_id)){
//                    $supplierIds[] = $s->suppliers_id;
//                }
//            }
//            if (empty($supplierIds)){
//                throw new \Exception('该spu未绑定工厂');
//            }
            $baseModel = new BaseModel();
            $makerName = $baseModel->GetUsers($demandMdl->maker_id)['account'] ?? '';
            $data = [
                'id' => $demandMdl->id,
                'spu' => $demandMdl->spu,
                'detail_url' => '/spu_quotation_list?id='.$demandMdl->id,
                'request_type' => 93, // 任务分类id
                'user_id' => $demandMdl->user_id,
                'maker_id' => $demandMdl->maker_id,
                'maker_name' => $makerName
            ];
            return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'，'.$e->getLine()];
        }
    }

    public function publishProofingTask($params)
    {
        try{
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给需求标识！');
            }
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $demandMdl = db::table('self_spu_proofing_demand')
                ->where('id', $params['id'])
                ->first();
            if (empty($demandMdl)){
                throw new \Exception('打样需求不存在！');
            }
            if (!in_array($demandMdl->status, [0, 1])){
                throw new \Exception('打样需求状态非待打样/打样中，不可打样！');
            }
            if ($demandMdl->user_id != $params['user_id']){
                throw new \Exception('非需求创建人不可发起打样！');
            }
//            $logMdl = db::table('self_spu_proofing_log')
//                ->where('proofing_id', $demandMdl->id)
//                ->get();
//            $check = [];
//            foreach ($logMdl as $log)
//            {
//                if (!isset($check[$log->sort])){
//                    $check[$log->sort] = 0;
//                }
//                $img = json_decode($log->img, true);
//                if (!empty($img)){
//                    $check[$log->sort] = 1;
//                }
//            }
//            foreach ($check as $k => $c){
//                if ($c == 0){
//                    throw new \Exception('第'.$k.'次存打样未被执行不可确认！');
//                }
//            }
            if ($demandMdl->num != 0){
                $logMdl = db::table('self_spu_proofing_log')
                    ->where('proofing_id', $demandMdl->id)
                    ->where('img', '<>', "")
                    ->where('sort', $demandMdl->num)
                    ->get();
                if ($logMdl->isEmpty()){
                    throw new \Exception('第'.$demandMdl->num.'轮打样未被执行！');
                }
            }
            $spuMdl = db::table('self_spu')
                ->where('id', $demandMdl->spu_id)
                ->first();
            if (empty($spuMdl)){
                throw new \Exception('SPU数据不存在！');
            }
//            $spuInfoMdl = db::table('self_spu_info_attr')
//                ->where('base_spu_id', $spuMdl->base_spu_id)
//                ->where('status', 1)
//                ->get();
//            if ($spuInfoMdl->isEmpty()){
//                throw new \Exception('该spu绑定数据为空！');
//            }
//            $supplierIds = [];
//            foreach ($spuInfoMdl as $s){
//                if (!empty($s->suppliers_id)){
//                    $supplierIds[] = $s->suppliers_id;
//                }
//            }
//            if (empty($supplierIds)){
//                throw new \Exception('该spu未绑定工厂');
//            }
//            $params['supplier_ids'] = array_unique($supplierIds);
            $num = $demandMdl->num + 1;
            if ($num > 3){
                throw new \Exception('打样不可超过三次！');
            }
            $baseModel = new BaseModel();
            $makerName = $baseModel->GetUsers($demandMdl->maker_id)['account'] ?? '';
            $data = [
                'id' => $demandMdl->id,
                'spu' => $demandMdl->spu,
                'detail_url' => '/spu_proofing_list?id='.$demandMdl->id,
                'request_type' => 95, // 任务分类id
                'user_id' => $demandMdl->user_id,
                'maker_id' => $demandMdl->maker_id,
                'maker_name' => $makerName
            ];
            return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'，'.$e->getLine()];
        }
    }
}//结束符